简体   繁体   中英

Setting numeric variables in a script (“set $i 1”) not working (“echo $i” empty)

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

The script is the code that follows

# !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

Here is what it yields:

entropy@3PY:~$ ./test4

As you can see it yields nothing while it should yield

1
2

thanks in advance

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"

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).


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"

Does this code works as desired?

#!/bin/bash
i=1
j=2

echo $i
echo $j

nombre=$i"_"$j.txt

echo $nombre

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM