-2

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?

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 1
    [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/995714). Please copy the console output and paste here – phuclv Sep 23 '21 at 13:04
  • 1
    You want `$(ls)`, not `'ls'`. And then [Expansion of variables inside single quotes in a command in Bash](https://stackoverflow.com/questions/13799789/expansion-of-variables-inside-single-quotes-in-a-command-in-bash). Pretty basic stuff, perhaps a Bash/shell scripting tutorial would be a good start? – Biffen Sep 23 '21 at 13:08
  • Also, [ParsingLs - Greg's Wiki](http://mywiki.wooledge.org/ParsingLs) and [ShellCheck – shell script analysis tool](https://www.shellcheck.net/). – Biffen Sep 23 '21 at 13:08
  • You are confusing the back-tick character `\`` with the single quote character `'`. In fact, because it is so easy to get wrong, the back-tick is archaic syntax. The modern equivalent is to enclose the command in `$( ... )`. For example: instead of `for LOOP in 'ls'`, use `for LOOP in $(ls)`. – Andrew Vickers Sep 23 '21 at 14:32
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 01 '21 at 04:57

1 Answers1

1

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:

  1. 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 than LOOP.
  2. 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.
Andrew Vickers
  • 2,504
  • 2
  • 10
  • 16