我有一个脚本,它在用户指定的目录中查找文件。
#!/bin/bash
# make sure about the correct input
if [ -z $1 ]
then
echo "Usage: ./script_name.sh path/to/directory"
else
DIR=$1
if [ $DIR = '.' ]
then
echo "Find files in the directory $PWD"
else
echo "Find files in the directory $DIR"
fi
find $DIR -type f -exec basename {} \;
fi
Run Code Online (Sandbox Code Playgroud)
如果我输入
$ ./script_name.sh .
Run Code Online (Sandbox Code Playgroud)
脚本给了我正确的替换 ./ 到 $PWD 并显示(例如)
$ Find files in the directory /root/scripts
Run Code Online (Sandbox Code Playgroud)
但是我无法决定如何将 ../ 替换 为层次结构中紧邻上方的目录的名称。如果我输入
$ ./script_name.sh ..
Run Code Online (Sandbox Code Playgroud)
脚本给了我输出
$ Find files in the directory ..
Run Code Online (Sandbox Code Playgroud)
有人知道如何将 ../ 替换为目录的实际名称吗?
ilk*_*chu 12
GNU coreutils 的realpath
命令就是这样做的。
/tmp/a$ realpath ..
/tmp
Run Code Online (Sandbox Code Playgroud)
但请注意,如果路径包含符号链接,它也会解决这些问题:
/tmp/b/c$ realpath ..
/tmp/x/y
Run Code Online (Sandbox Code Playgroud)
(这里,/tmp/b
是一个符号链接/tmp/x/y/
)
这可能与 shell 对cd ..
. 例如cd ../..
from /tmp/b/c
in Bash 将新路径显示为/tmp/
,而不是/tmp/x
。