0

I have script which is taking one argument ($1). So I run it like this: bash script.sh file1.txt. But when I want to substitute more files (bash script.sh *) then he only takes one file from all. How can I make it work? Should be there another script which substitute all files from folder as $1 into script.sh or is there easier way?

#!/bin/bash
sed -i '/^$/d' $@
declare -a command
while read -r line
do
  [[ "$line" =~ ^secretcommand$ ]] || continue
  read -r cmd || break
  eval "$cmd"
  break
done<"$@"

It's not working with "$@".

Can you help me please?

Anna
  • 39
  • 1
  • 9

1 Answers1

1

The loop in your code is designed to iterate over all lines of a given file. You need to add an outer loop to iterate over every file.

#!/bin/bash
sed -i '/^$/d' "$@"
for file in "$@"
  while read -r line
  do
    [[ "$line" =~ ^secretcommand$ ]] || continue
    read -r cmd || break
    eval "$cmd"
    break
  done<"$file"
done

Please note you need to quote "$@" whenever you want to use it as an argument list to a command (such as your sed command above).

Fred
  • 6,590
  • 9
  • 20
  • Thank you so much for help! It works properly when I run it like this: "bash script.sh *", but when I want to use it in this way: "sh script.sh *" Then my output has some issues and isn't working much. Why is that? What's difference in running script as bash and sh? I used this script to find in file word "secretcommand" and in the next line is always the command which i want to run in console. I was deleting with sed empty lines, because sometimes in my files there are some of those empty lines between key word and command and my script works only when command is right in the next line. – Anna Jan 28 '17 at 13:12
  • The code I suggested uses bash-specific syntax (your question is tagged `bash`). `sh` may be a different shell, so this syntax will not work if run by `sh`. Have you included the first line (with the `#!/bin/bash`) in your script? – Fred Jan 28 '17 at 13:16
  • Have you included the first line (with the `#!/bin/bash`) in your script? If so, you can `chmod u+x` the script and run it as if it were a program (the right shell will be used automatically). – Fred Jan 28 '17 at 13:23
  • Oh, I understand now. I'm gonna try thing with chmod. Thank you! – Anna Jan 28 '17 at 13:34
  • And yes, I included first line #!/bin/bash – Anna Jan 28 '17 at 13:35