LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Scripting queries - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/scripting-queries-newbie-4175519232/)

LYC 09-17-2014 10:55 PM

Scripting queries - Newbie
 
Hi,

I have a file containing a list of commands with argument, how to run the commands automatically?

Assuming the contents of file "command2run" are as follows:
ls -ls
ls -la
ls -L

I tried the following:
for i in `cat command2run`
do
$i
done

The arguments were ran seperately instead of "ls -ls". Please advise?

Thanks in advance.

grail 09-17-2014 11:29 PM

Ok ... a few things:

1. Please use [code][/code] tags around code and data

2. Do not use a for loop to read a file as it will under go word splitting (which is why you see separate entries). Use a while loop

3. If you are looking to execute the items in the file you can source it, ie use source or . prior to file name on the command line
Code:

$ . command2run

LYC 09-18-2014 10:34 PM

Hi,

I used . command2run but it just not able to go back to the command prompt after it finished. Not even I do and control-c.

SAbhi 09-18-2014 11:31 PM

Then use "source" Or a little help for you to use while to read a file:

Code:

while read line; do <do something here with $line>; done< input_filename

grail 09-19-2014 01:33 AM

Ok, not sure what to tell you as it works as described for me.

However, here are some assumptions I have made which may be incorrect:

1. Your standard shell is bash, to check:
Code:

$ echo $SHELL
/bin/bash

2. Your file contains the following data:
Code:

$ cat command2run
ls -ls
ls -la
ls -L

3. When run I receive:
Code:

$ . command2run
total 16
12 -rwxr-xr-x 1 grail users 10444 17.09.2014 18:07 bashrc.tar.gz*
 4 -rwx------ 1 grail users    46 17.09.2014 18:28 d.sh*
total 64
drwxr-xr-x 2 grail users  4096 17.09.2014 18:26 ./
drwxr-xr-x 4 grail users  4096 19.09.2014 14:22 ../
-rw------- 1 grail users 19679 14.09.2014 16:04 .bashrc
-rw------- 1 grail users 11025 14.09.2014 15:24 .bashrc_help
-rw------- 1 grail users  7828 14.09.2014 15:24 .bashrc_help.no_color
-rwxr-xr-x 1 grail users 10444 17.09.2014 18:07 bashrc.tar.gz*
-rwx------ 1 grail users    46 17.09.2014 18:28 d.sh*
bashrc.tar.gz*  d.sh*

Obviously your output will be different

kaushalpatel1982 09-19-2014 05:49 AM

run it with sh command directly

Quote:

sh command2run


All times are GMT -5. The time now is 10:54 AM.