Method for obtaining path file name in Linux system

  
        

This article mainly introduces the method of obtaining the file name of the path in the Linux system. The text summarizes two. The friends who need it can refer to the following

The code is as follows:

[root @dabu.info ]#basename /root/aaa/bbb/dabu.txt

Display:

The code is as follows:

dabu.txt #Get the file name of the path< Br>

How to get the path of the script file in the shell script?

Method 1:

The code is as follows:

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

[[email protected] ]#echo $DIR

But like this dirname "$0" This way of writing, you will get the wrong result when you encounter the source command.

Method 2:

The code is as follows:

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

The above line of commands can get the absolute wheel diameter of the script, no matter where you call it.

But if you have a soft link, you can't use it. Therefore, in order to correctly parse the soft link to the script, we can use the following multi-line commands:

The code is as follows:

SOURCE="${BASH_SOURCE[0]}"< Br>

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 )"

can also be used with the source, bash -c command. Br>

However, if you use cd to switch to another directory in the script, the above command will not wait for the correct result when running the above command fragment. See the article about the $CDPATH trap. To understand how it works, you can run the following code:

The code is as follows:

#!/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'"< Br>

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" )"

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

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

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

fi

echo "DIR is '$DIR'"< Br>

Copyright © Windows knowledge All Rights Reserved