Issue
I write a code in Bash script and the Linux does not run it correctly and printed character instead of character’s value.
Can anyone help me?
Solution
Aside from the confusion between backtick and '
, you are also over-using the sub-shell syntax. You do not need to use echo $(cat $LOOP)
. You can just run cat $LOOP
directly.
#!/bin/bash
for FILE in $(ls); do
echo "Here is ${file}:"
cat ${FILE}
echo ""
done
A couple of points of style as well:
- Name your variables after the thing they represent. The loop is iterating over files in the current directory, so the name
FILE
is more descriptive thanLOOP
. - It is a good idea to get in the habit of enclosing your variable references in
${ ... }
instead of just prefixing them with$
. In simple scripts like this, it does not make a difference, but when your scripts get more complicated, you can get into trouble when you do not clearly delineate variable names.
Answered By - Andrew Vickers