Windows XP Windows 7 Windows 2003 Windows Vista Windows教程綜合 Linux 系統教程
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟件教程
 Windows教程網 >> Linux系統教程 >> Linux系統常見問題解答 >> Linux系統中獲取路徑的文件名的方法

Linux系統中獲取路徑的文件名的方法

日期:2017/1/20 17:36:07      編輯:Linux系統常見問題解答

這篇文章主要介紹了Linux系統中獲取路徑的文件名的方法,文中總結出了兩條,需要的朋友可以參考下

  代碼如下:

  [[email protected] ]#basename /root/aaa/bbb/dabu.txt

  顯示:

  代碼如下:

  dabu.txt #獲取路徑的文件名

  shell腳本中如何獲得腳本文件所在路徑?

  方法一:

  代碼如下:

  [[email protected] ]#DIR=$(cd "$(dirname "$0")"; pwd)

[[email protected] ]#echo $DIR

  但是像這種dirname "$0"這種寫法,在遇到source命令時會得到錯誤的結果。

  方法二:

  代碼如下:

  [[email protected] ]#echo "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

  上面一行命令可以獲得腳本的絕對輪徑,無論你在何處調用這個腳本。

  但是如果含有軟鏈接,就無法使用了。所以,我們為了能正確解析指向腳本的軟鏈接,可以使用下面的多行命令:

  代碼如下:

  SOURCE="${BASH_SOURCE[0]}"

  while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink

  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

  SOURCE="$(readlink "$SOURCE")"

  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located

  done

  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

  也可與source,bash -c命令使用

  但是,如果你在腳本中使用先cd切換到其他目錄,在運行時上面的命令片段時,則上面的命令不能等到正確的結果。可以參考關於$CDPATH 陷阱的文章。想理解它如何其作用的,可以運行下面的代碼:

  代碼如下:

  #!/bin/bash

SOURCE="${BASH_SOURCE[0]}"

  while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink

  TARGET="$(readlink "$SOURCE")"

  if [[ $SOURCE == /* ]]; then

  echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"

  SOURCE="$TARGET"

  else

  DIR="$( dirname "$SOURCE" )"

  echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"

  SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located

  fi

  done

  echo "SOURCE is '$SOURCE'"

  RDIR="$( dirname "$SOURCE" )"

  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

  if [ "$DIR" != "$RDIR" ]; then

  echo "DIR '$RDIR' resolves to '$DIR'"

  fi

  echo "DIR is '$DIR'"

Copyright © Windows教程網 All Rights Reserved