我想在苹果和香蕉这样的脚本中找到变量值,并用苹果代替Apple和香蕉代替香蕉。基本上,如果脚本识别作为参数传递的Apples,它应该将其更改为Apple,反之亦然。
不寻找Sed或正则表达式。
fresh_fruits的两个参数是苹果,香蕉
水果= $ {fresh_fruits}
答案 0 :(得分:1)
当你说“作为参数传递”时,我假设你指的是修改位置参数的值。
一种方法是使用关联数组将现有值映射到所需的值:
#!/usr/bin/env bash
# this code requires bash 4.0 -- fail if run with non-bash or older shell
if [ -z "$BASH_VERSION" ] || [[ $BASH_VERSION = [1-3]* ]]; then
echo "ERROR: Script requires bash 4.0 or newer" >&2
exit 1
fi
# here's the important part: map the values we want to replace to the new versions
declare -A parameter_map=(
[Apples]=Apple
[Bananas]=Banana
)
# build an args array containing converted versions of our arguments
args=( )
for arg; do
if [[ ${parameter_map[$arg]+exists} ]]; then
args+=( "${parameter_map[$arg]}" )
else
args+=( "$arg" )
fi
done
# update the script's arguments based on the above
set -- "${args[@]}"
# for test purposes, print all our arguments
echo "Arguments as follows:"
printf ' - %q\n' "$@"
如果以./yourscript Apples Bananas Pear
运行,则输出为:
Arguments as follows:
- Apple
- Banana
- Pear
如果我们不需要更新整个参数列表,那么以符合POSIX的方式更容易实现,没有需要数组(关联或其他):
#!/bin/sh
var=$1
case $var in
Apples) var=Apple ;;
Bananas) var=Banana ;;
esac
echo "New value: $var"