-1

I want to loop over some values and I know I can simply use a for loop but is there any other way that I can replace a variable value in a command at the end of the command?

Somewhat like

echo 11"$p" < 8 #toprint 118

echo 11"$p" < 9 #toprint 119

echo 11"$p" < a #toprint 11a

I want to be able to replace certain variables with my value but at the end of the command. I know there are multiple ways to do this so I'm not asking for other ways.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

2 Answers2

1
( read p && echo "11$p" ) <<<8

or

{ read p && echo "11$p"; } <<<8

if the variable is to keep its value after the command.

The <<< is a here-string redirection. It redirects a single string into a command or utility. Here, we use it to send the digit into the subshell or compound command. This compound command reads the value, then prints it as part of a string.

You can't use <8 as that would try to read from a file called 8.

Kusalananda
  • 333,661
1

If your values are in an array, no need to loop over them, just do:

values=(8 9 a)
printf '11%s\n' "${values[@]}"

Same if they are in different variables:

a=8 b=9 c=a
printf '11%s\n' "$a" "$b" "$c"

If the input comes from stdin, you can use xargs:

xargs printf '11%s\n' << EOF
8 "9"
'a'
EOF

(above showing different kinds of quoting or argument delimiter supported by xargs).

Or use things like:

sed 's/^/11/' << EOF
8
9
a
EOF

or

awk '{print "11" $0}' << EOF
8
9
a
EOF

Generally, in shell scripting, you don't want to write explicit loops. The looping is done by those text utilities that process their input one line at a time or one argument at a time.