我有一个 shell 脚本,可以从用户那里获取目录路径,但我需要检查目录是否为空。如果用户将他的主路径与~
而不是绝对路径,所以我无法检查它ls
echo "Specify your project root directory. For example: ~/Base/project1"
read directory
if [ ! -z "$directory" ]
then
if [ "$(ls -A "$directory")" ]
then
echo Directory $directory is not empty
else
echo The directory $directory is empty '(or non-existent)'
fi
directory="$directory"
else
echo "No root directory specified. Exiting.."
exit;
fi
我收到错误: ls 无法使用 ~ 读取路径,如何在检查目录为空之前扩展它?
鲁斯兰的使用建议eval
只要目录规范有效,就保证可以工作。但是,如果用户输入恶意内容(或者只是意外输入会导致副作用的内容),它确实会使您面临任意代码执行的风险。
如果你的外壳有printf
支持%q
(Bash 就是这么做的),你可以用它来转义路径中的所有危险字符,然后让 Bash 扩展它:eval
:
if [ "${directory:0:1}" == \~ ]; then
eval directory="$(printf '~%q' "${directory#\~}")"
fi
否则,您可以手动扩展波形符。赛勒斯的答案适用于像这样的路径~/some/path
(未指定用户的情况),但对于像这样的路径会失败~somebody/some/path
.
为了处理这种情况,我们可以使用以下命令查找用户的主目录getent http://man7.org/linux/man-pages/man1/getent.1.html并手动扩展路径:
prefix=${directory%%/*}
if [ "$prefix" == \~ ]; then
# Implicitly use current user.
user=$USER
else
# Parse user from tilde prefix.
user=${prefix#\~}
fi
# Get the home directory of the user. Only expand if the expanded directory exists.
homedir=$(getent passwd -- "$user" | cut -d: -f6)
if [ -d "$homedir" ]; then
# Replace the tilde prefix with the absolute path to the home directory.
directory=$homedir${directory#$prefix}
fi
这模仿了 shell 在无效主目录规范中的行为(例如,~baduser/
) 将保持原样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)