› Forums › Basic skills › Programming › Shell scripting (in bash) › Passing values between scripts
- This topic has 1 reply, 1 voice, and was last updated 9 years ago by Simon.
-
AuthorPosts
-
-
December 2, 2015 at 12:58 #1027
Quite often you will need to use several scripts at once, and will need to pass values between them.
Let’s start with the simple case of passing a value on the command line to a single script. Here’s the script:
#!/bin/bash # items passed on the command line are available as $1 , $2 , $3 , etc # it is good practice to copy those into variables with meaningful names # and not to use $1 etc throughout the script MYVARIABLE=$1 echo "The first argument passed on the command line was "${MYVARIABLE}
You might also need to change the path to bash on the first line, to suit your operating system. Save it in a file (I’ll assume you saved it in a file called scripts/simple_script.sh). First, make it executable:
$ chmod +x ./scripts/simple_script.sh
now let’s run it:
$ ./scripts/simple_script.sh argument
I’ve attached a zip file containing everything you need.
Attachments:
You must be logged in to view attached files. -
December 2, 2015 at 13:15 #1029
Next, let’s write a script that calls another script, and passes a value to it on the command line. Here are the two scripts:
#!/bin/bash MYVARIABLE=$1 echo "This is the child script and the value passed was" ${MYVARIABLE}
and
#!/bin/bash # this is the parent script echo "This is the parent script and it is about to run the child script three times" ./scripts/child.sh one ./scripts/child.sh two ./scripts/child.sh three echo "Now we are back in the parent script" echo "Let's get smarter and write code that is easier to maintain" for COUNT in one two three do ./scripts/child.sh $COUNT done echo "Pretty nice - but we can do even better and read in the list from a file" for FRUIT in `cat lists/fruit_list.txt` do ./scripts/child.sh ${FRUIT} done echo "Much better. Now let's save the output to a file so we can inspect it later" echo "This method will overwrite the contents of the file, if it already exists" (for FRUIT in `cat lists/fruit_list.txt` do ./scripts/child.sh ${FRUIT} done) > output.txt echo "Another way is to append lines to an existing file" echo "This line will appear in the file" >> output.txt for FRUIT in `cat lists/fruit_list.txt` do ./scripts/child.sh ${FRUIT} >> output.txt done echo "Now you need to look at the file just created, called output.txt" echo "For example, you could now type 'cat output.txt' or open it in Aquamacs"
and the file fruit_list.txt contains
apples bananas pears oranges
now let’s run it
$ ./scripts/parent.sh
I’ve attached a zip file containing everything you need.
Attachments:
You must be logged in to view attached files.
-
-
AuthorPosts
- You must be logged in to reply to this topic.