1

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

1
  • As an aside -- you might want #!/bin/bash or #!/usr/bin/env bash as your shebang, or #!/bin/sh if you really wanted to write POSIX sh instead of bash (despite the question being tagged for the latter). #!/usr/bin isn't a valid shebang, nor is # !usr/bin, and a script starting with either of those won't run correctly when started from something other than a shell. Commented Jan 20, 2017 at 17:25

2 Answers 2

5

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"
Sign up to request clarification or add additional context in comments.

Comments

0

Does this code works as desired?

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

echo $i
echo $j

nombre=$i"_"$j.txt

echo $nombre

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.