相关疑难解决方法(0)

使用函数测试未设置的Bash变量

一个简单的Bash变量测试:

${varName:?    "${varName} is not defined"}
Run Code Online (Sandbox Code Playgroud)

我想把它放在一个函数中来重复使用它.怎么样?

以下失败

#
# Test a variable exists
tvar(){
 val=${1:?    "${1}    must be defined, preferably in $basedir"}
 if [ -z ${val}  ]
     then 
     echo Zero length value 
 else
     echo ${1} exists, value ${1}
 fi
}
Run Code Online (Sandbox Code Playgroud)

即如果测试失败,我需要退出.

variables bash undefined

28
推荐指数
4
解决办法
5万
查看次数

在函数内部使用Bash间接变量赋值

我有一个脚本,用户输入需要进行评估数次,该解决方案IM工作就是把评估位转换成函数,只需调用函数每次我需要评估的输入时间.问题是,当我试图更新$1变量(引用函数的第一个变量参数)时,我收到错误消息"$ VARIABLE command not found".

这是代码:

function input_handler() {
 if is_integer $1; then
  selid="$1 -1"
  if [[ "$1" -le "0" ]]; then
   echo "Please use a simple positive number!"
  else
   if [[ "$1" -le "${#array[*]}" ]]; then
    eval $1="${array[selid]}"
    echo "Ok, moving on..."
   else
    echo "That number seems too large, try again?"
   fi
  fi
 else
  if [ -e $2/$1 ]; then
   echo "Ok, moving on..."
  else
   echo "That item is not on the list, try again!"
  fi
 fi …
Run Code Online (Sandbox Code Playgroud)

variables bash function

5
推荐指数
1
解决办法
2899
查看次数

标签 统计

bash ×2

variables ×2

function ×1

undefined ×1