【问题标题】:Finding variable values passed as parameter and replacing with another variable value in Bash script在 Bash 脚本中查找作为参数传递的变量值并替换为另一个变量值
【发布时间】:2018-05-16 00:59:49
【问题描述】:

我想在脚本中找到变量值,例如 Apples 和 Bananas,并将值替换为 Apple 用于 Apples,将 Banana 替换为 Bananas。基本上,如果脚本识别作为参数传递的 Apple,它应该将其更改为 Apple,反之亦然。

不寻找 Sed 或正则表达式。

fresh_fruits 的两个参数是 Apples、Bananas

水果=${fresh_fruits}

【问题讨论】:

  • 更改参数,意思是你想改变$1所指的东西,还是你只是设置foo=$1然后想更新$foo?通过在其中包含一些实际代码来明确您正在寻找的内容,这个问题将得到很大帮助。
  • 您是想在存在s 时修剪尾随s,还是匹配特定字符串ApplesBananas
  • ...无论哪种情况,您都应该查看the case statement,而在前者中,您绝对应该查看parameter expansion
  • fresh_fruits 的两个参数是 Apples,Bananas Fruits=${fresh_fruits}
  • edit 提出这个问题——与评论字段相比,它为清晰的描述提供了更多的空间。请参阅帮助中心中的 minimal reproducible example 定义,以获取有关提供有效说明您的问题的代码的指导。

标签: bash shell variables environment-variables


【解决方案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"

【讨论】:

  • 我在脚本末尾有一个路径,参数如下 home/$fresh_fruits/working
  • 我可以在哪里粘贴您为该脚本执行提供的解决方案?是在路径之前还是在脚本的乞求处?请帮忙
  • 那么你要替换的是变量value,而不是位置参数?这样就容易多了。
  • ...也就是说,如果放在脚本的开头,原始代码将替换完整的参数列表($1$2 等)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2013-08-06
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 2019-03-11
相关资源
最近更新 更多