Jov*_*nda 22 command-line bash scripts alias
我有以下脚本。这是一个简单的测试用例,其中a是任何字符串值并且b应该是路径。
#!/bin/bash
alias jo "\
echo "please enter values "\
read a \
read -e b \
echo "My values are $a and $b""
Run Code Online (Sandbox Code Playgroud)
但是,每当我尝试执行 ./sample.sh 时,都会出现以下错误:
./sample.sh: line 3: alias: jo: not found
./sample.sh: line 3: alias: echo please: not found
./sample.sh: line 3: alias: enter: not found
./sample.sh: line 3: alias: values: not found
./sample.sh: line 3: alias: read a read -e b echo My: not found
./sample.sh: line 3: alias: values: not found
./sample.sh: line 3: alias: are: not found
./sample.sh: line 3: alias: and: not found
./sample.sh: line 3: alias: : not found
Run Code Online (Sandbox Code Playgroud)
当我尝试时,source sample.sh我得到以下信息:
a: Undefined variable.
Run Code Online (Sandbox Code Playgroud)
我的目标是将其设为别名,以便我可以获取此脚本的源代码并仅运行别名来执行命令行。有人可以看看这个并让我知道错误是什么吗?
ste*_*ver 21
你在这里有几个问题
与 in csh、 in bash(和其他类似 Bourne 的 shell)不同,别名用=符号分配,例如alias foo=bar
引号不能这样嵌套;在这种情况下,您可以在别名周围使用单引号并在其中使用双引号
反斜线\是续行字符:语法,它使你的命令转换为单一线(你想的正好相反)
所以
#!/bin/bash
alias jo='
echo "please enter values "
read a
read -e b
echo "My values are $a and $b"'
Run Code Online (Sandbox Code Playgroud)
测试:首先我们获取文件:
$ . ./myscript.sh
Run Code Online (Sandbox Code Playgroud)
然后
$ jo
please enter values
foo bar
baz
My values are foo bar and baz
Run Code Online (Sandbox Code Playgroud)
如果您想在脚本中使用别名,请记住别名仅在交互式 shell 中默认启用:要在脚本中启用它们,您需要添加
shopt -s expand_aliases
Run Code Online (Sandbox Code Playgroud)
不管上面的一切,你应该考虑使用 shell 函数而不是像这样的别名
gle*_*man 11
习惯在 POSIX 类型的 shell 中使用函数。您没有任何引用问题:
jo () {
read -p "Enter value for 'a': " -e a
read -p "Enter value for 'b': " -e b
echo "My values are $a and $b"
}
Run Code Online (Sandbox Code Playgroud)