如何通过读入bash传递变量

时间:2014-11-26 18:53:45

标签: bash shell variables mkdir

我试图制作一个要求目录路径的脚本,然后创建该目录。我希望能够将变量传递给read builtin所以路径名,所以我不必输入完整的路径:

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

没有扩张。关于如何使其发挥作用的任何想法?

3 个答案:

答案 0 :(得分:1)

这有点麻烦,但有一个选择是使用-e标志告诉read使用Readline来获取输入,然后在输入后使用Readline扩展该行,但是在点击之前输入

$ read -e directory
$HOME/dir

现在键入 Meta - Control - e ,Readline将扩展输入,就好像它在执行前一样被处理shell命令。 (请注意,Meta键可能是Alt或Esc,具体取决于您的终端设置。)

答案 1 :(得分:1)

通过尝试使用read获取目录,实际上会使事情变得更加困难。除非您绝对要求使用read,否则最好将目录传递给函数as an argument。例如:

function make_dir {
    [ -n "$1" ] || {
        printf "\n usage: make_dir <path_to_create>\n\n"
        return 1
    }
    mkdir -p "$1" || {
        printf "\n error: unable to create '$1', check permissions\n\n"
    }
}

示例:

$ function make_dir {
>     [ -n "$1" ] || {
>         printf "\n usage: make_dir <path_to_create>\n\n"
>         return 1
>     }
>     mkdir -p "$1" || {
>         printf "\n error: unable to create '$1', check permissions\n\n"
>     }
> }

$ make_dir $HOME/temp_dir

$ ls -al temp_dir
total 8
drwxr-xr-x  2 david david 4096 Nov 26 15:34 .
drwxr-xr-x 76 david david 4096 Nov 26 15:34 ..

$ make_dir

usage: make_dir <path_to_create>

当您将目录传递给函数as an argument而不是使用read时,您可以轻松地将功能调整为take/create multiple directories

function make_dir {
    [ -n "$1" ] || {
        printf "\n usage: make_dir <path_to_create> [path2, ..]\n\n"
        return 1
    }
    for i in "$@" ; do
        mkdir -p "$i" || {
            printf "\n error: unable to create '$i', check permissions\n\n"
        }
    done
}

示例:

$ make_dir temp_dir_{1..3}
$ ls -1d temp_*
temp_dir_1
temp_dir_2
temp_dir_3

答案 2 :(得分:0)

更改以下行:

mkdir "$directory"

eval mkdir -p "$directory"