Partial variable substitution in script

I have a script.

filecreatenew ()  {
        touch /usr/src/$1_newfile.txt
        var=$1
        echo $var
        touch /usr/src/$var_newfile_with_var.txt
}

filecreatenew myfile

Its creating file /usr/src/myfile_newfile.txt as the variable $1 is correctly used. When $ is assigned to $var, the variable in $var is echoed fine, but the file is not getting created. How can I get the file myfile_newfile_with_var.txt correctly with the above script. ie the variable passed from $1 to $var should work in the line "touch /usr/src/$var_newfile_with_var.txt"

Try:

touch "/usr/src/${var}_newfile_with_var.txt"

Otherwise the script will be trying to expand the non-existing variable $var_newfile_with_var . An underscore can be used as part of a variable name.

--edit--
In the case of

touch /usr/src/$1_newfile.txt

The braces are not strictly required, because $1 will be interpreted as a positional parameter no matter what follows (also - and perhaps because of this - variable names may not begin with a number).

But it will not hurt to use braces for clarity:

touch "/usr/src/${1}_newfile.txt"
1 Like

Scrtinizer,

It worked thanks