0

I tried to execute commands read it from txt file. But only 1st command is executing, after that script is terminated. My script file name is shellEx.sh is follows:

echo "pwd" > temp.txt
echo "ls" >> temp.txt
exec < temp.txt
while read line
do
exec $line
done
echo "printed"

if I keep echo in the place of exec, just it prints both pwd and ls. But i want to execute pwd and ls one by one.

o/p am getting is:

$ bash shellEx.sh
/c/Users/Aditya Gudipati/Desktop

But after pwd, ls also need to execute for me. Anyone can please give better solution for this?

aditya gudipati
  • 103
  • 1
  • 2
  • 5
  • Is "/c/Users/Aditya Gudipati/Desktop" a single path and do you experience problems with white space, or is it two tokens? – user unknown Mar 17 '18 at 11:00
  • Why are you reading the file line by line, instead of just sourcing the file with `. temp.txt`? – chepner Mar 17 '18 at 16:26

2 Answers2

2

exec in bash is meant in the Unix sense where it means "stop running this program and start running another instead". This is why your script exits.

If you want to execute line as a shell command, you can use:

line="find . | wc -l"
eval "$line"

($line by itself will not allow using pipes, quotes, expansions or other shell syntax)

To execute the entire file including multiline commands, use one of:

source ./myfile # keep variables, allow exiting script
bash myfile     # discard variables, limit exit to myfile
that other guy
  • 116,971
  • 11
  • 170
  • 194
-1

A file with one valid command per line is itself a shell script. Just use the . command to execute it in the current shell.

$ echo "pwd" > temp.txt
$ echo "ls" >> temp.txt
$ . temp.txt
chepner
  • 497,756
  • 71
  • 530
  • 681