AZo*_*rin 42 linux bash shell terminal command-line
所以我的问题是如何使用Linux中的终端命令将文件参数传递给我的bash脚本?目前我正在尝试在bash中创建一个程序,该程序可以从终端获取文件参数并将其用作程序中的变量.例如我myprogram --file=/path/to/file在终端中运行
.
#!/bin/bash
File=(the path from the argument)
externalprogram $File (other parameters)
Run Code Online (Sandbox Code Playgroud)
如何通过我的程序实现这一目标?
Dav*_*d Z 56
如果你只是运行你的脚本,它会更容易(并且更"正确",见下文)
myprogram /path/to/file
Run Code Online (Sandbox Code Playgroud)
然后你可以访问脚本中的路径$1(对于参数#1,类似地$2是参数#2,等等)
file="$1"
externalprogram "$file" [other parameters]
Run Code Online (Sandbox Code Playgroud)
要不就
externalprogram "$1" [otherparameters]
Run Code Online (Sandbox Code Playgroud)
如果你想从类似的东西中提取路径--file=/path/to/file,那通常是用getoptsshell函数完成的.但这比仅仅参考更复杂$1,而且,类似--file=的开关是可选的.我猜你的脚本需要提供一个文件名,所以在一个选项中传递它是没有意义的.
les*_*ana 21
您可以使用getopt来处理bash脚本中的参数.getopt的解释并不多.这是一个例子:
#!/bin/sh
OPTIONS=$(getopt -o hf:gb -l help,file:,foo,bar -- "$@")
if [ $? -ne 0 ]; then
echo "getopt error"
exit 1
fi
eval set -- $OPTIONS
while true; do
case "$1" in
-h|--help) HELP=1 ;;
-f|--file) FILE="$2" ; shift ;;
-g|--foo) FOO=1 ;;
-b|--bar) BAR=1 ;;
--) shift ; break ;;
*) echo "unknown option: $1" ; exit 1 ;;
esac
shift
done
if [ $# -ne 0 ]; then
echo "unknown option(s): $@"
exit 1
fi
echo "help: $HELP"
echo "file: $FILE"
echo "foo: $FOO"
echo "bar: $BAR"
Run Code Online (Sandbox Code Playgroud)
也可以看看:
man getoptDan*_*ing 12
Bash支持一个名为"位置参数"的概念.这些位置参数表示在调用Bash脚本时在命令行上指定的参数.
位置参数由名称简称$0,$1,$2...等等.$0是脚本本身的名称,是脚本$1的第一个参数,$2第二个,等等$*表示所有位置参数,除了$0(即以...开头$1).
一个例子:
#!/bin/bash
FILE="$1"
externalprogram "$FILE" <other-parameters>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
173854 次 |
| 最近记录: |