【发布时间】:2014-11-26 18:53:45
【问题描述】:
我正在尝试制作一个脚本来询问目录路径,然后创建该目录。我希望能够将变量传递给 read 内置路径名,这样我就不必输入完整路径:
function make_dir {
echo "What is the path of the directory to be created?"
read directory
mkdir "$directory"
}
所以我会输入:
make_dir
What is the path of the directory to be created?
$HOME/temp_dir
mkdir: cannot create directory `$HOME/temp_dir': No such file or directory
所以我想将 $HOME 扩展为 /home/user/ 和创建目录 /home/user/temp_dir 的脚本,但我似乎无法让扩展工作。
如果我将下面的make_dir函数修改为show_dir
function show_dir {
echo "What is the path of the directory to be created?"
read directory
echo "The directory is $directory"
}
然后我输入$HOME/temp_dir 并得到以下信息:
make_dir
What is the path of the directory to be created?
$HOME/temp_dir
The directory is $HOME/temp_dir
没有扩展。关于如何让它发挥作用的任何想法?
【问题讨论】:
-
唯一的答案是
eval,这不是一个好的解决方案。使用read -e选项卡完成可能会为您展开它,并且任何展开变量的读取行绑定(如meta-ctrl-e或esc ctrl-e)都会在您按Enter 之前展开它。 -
感谢您的回复,在
mkdir "$directoy"前面添加eval似乎可行,您能帮我理解为什么这不是一个好的解决方案吗? -
@BrianAlbertMonroe 问题是如果
$directory扩展为some string; rm -rf /*之类的东西。eval然后得到字符串echo some string; rm -rf /*来执行。
标签: bash shell variables mkdir