Linux Shell Script to execute another shell script using variables defined in multiple text files
I'm trying to write a Linux Shell Script to do some automation on my server. I'm using Ubuntu 11.04 by the way.
Basically, the process is as follows:
A. I create multiple text files using PHP in a directory (/home/mydir). These text files are stubs of a shell script, and they contain only variable definitions. Here is a sample of what might be in one of the files.
username="myusername1"
password="mypassword1"
othersettings="othersettings1"
B. I have a setup shell script that references the above variables. Below is a part of what may be in the script:
#!/bin/bash
mkdir /home/newdir/$username
I'm trying to write an activation shell script that will find out how many of these files are in the /home/mydir and then execute the setup shell script for each one of the files in the directory. So, for example, if I have 5 files with 5 different username, password, etc. the setup script will be run 5 times using the variables in each of the text files to complete the tasks defined in this script.
I'd appreciate some assistance on how to write such a script. The way my mind is working is that I should use maybe ls -1 /home/mydir | grep .txt
to get all txt files, then extract them to an array, and then iterate and execute the script, but I'm not a shell scripti开发者_C百科ng expert so I need some assistance with the syntax. If shell scripting was PHP, it wouldn't have been a problem for me, but alas, it is not.
Thanks in advance.
The way to do this in shell is something like this:
for f in /home/mydir/*.txt; do
. "$f" # source settings file
mkdir "/home/newdir/$username"
done
But as I mentioned in my comment, you could just write your script in PHP.
#!/usr/bin/php
<?php
...
?>
EDIT
Your code works, I just edited it for calling a shell script within a shell script, which is what I really wanted to do. So the below code works too.
#!/bin/bash
for f in /home/dir/*.txt
do
. "$f"
. /path/to/setup-shell-script #referenced in B of the original question
done
This is what the .
or source
command is for in shell scripts; it will read the contents of the argument (file) and execute them. Beware of people forcing your script to use a file you did not intend them to use. Note that C shell includes the source
command (Bourne shell only supported .
); Bash provides both.
. /home/mydir/mystery_settings_file
mkdir /home/newdir/$username
Note that if you write:
. mystery_settings_file
the shell will search for it using $PATH, but the file only has to be readable (it does not need to be executable). This can be quite useful.
精彩评论