在脚本中设置数字变量("set $ i 1")无效("echo $ i"为空) [英] Setting numeric variables in a script ("set $i 1") not working ("echo $i" empty)

查看:284
本文介绍了在脚本中设置数字变量("set $ i 1")无效("echo $ i"为空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我需要bash脚本的帮助,该脚本必须在给定两个数字变量的情况下生成一个字符串.该字符串将用于生成文件名,但是当我测试名称生成代码时,它什么也没产生

As the title says I need help with a bash script that has to generate a string given two numeric variables. That string will be used to generate a file name, but when I test the name generation code it yields nothing

脚本是下面的代码

# !usr/bin
set nombre
declare -a i
declare -a j

set $i  1
set $j  2

set nombre "$i\_$j.txt"

echo $i
echo $j

这里是产生的东西:

entropy@3PY:~$ ./test4

如您所见,它不会产生任何收益,而应该产生

As you can see it yields nothing while it should yield

1
2

预先感谢

推荐答案

set不用于为常规变量赋值;它用于设置位置参数的值或修改壳选项.您需要定期分配.

set is not used to assign values to regular variables; it is used to set the values of the positional parameters or to modify shell options. You need a regular assignment.

i=1
j=2
nombre="${i}_$j.txt"

echo "$i"
echo "$j"
echo "$nombre"

无需在分配之前声明变量;必要时,赋值会创建一个变量. declare命令更多地是关于在名称上设置 (例如,-a会将变量标记为数组变量,您在这里 不需要执行此操作).

There is no need to declare variables prior to assignment; assignment creates a variable if necessary. The declare command is more about setting attributes on a name (-a, for instance, would mark the variable as an array variable, something you do not need here).

set 的工作方式为例,请考虑

As an example of how set does work, consider

echo "First positional parameter: $1"
echo "Second positional parameter: $2"
set foo bar  # $1=foo, $2=bar
echo "First positional parameter: $1"
echo "Second positional parameter: $2"

这篇关于在脚本中设置数字变量("set $ i 1")无效("echo $ i"为空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆