0

I'd like to create a script which creates another script using 2 parameters. The second script should use its own parameter. The problem I keep running into is that the the last echo puts the argument of the first script into the second. So how do I make my second script take a parameter? I'd like to know how to do this Here's my first script:

#! /bin/bash
MY_FILE=$1
MY_PATH=$2
touch $MY_PATH/$MY_FILE
echo "#! /bin/bash" > $MY_FILE
echo "ps -u $1 -o comm=CMD -o pid,ppid,user,uid,gid" >> $MY_FILE

2 Answers 2

1

If you read the manual for the bash shell, double-quoting preserves the literal value of characters within the quotes, except for '$', '`' and '\'. So, the line you wrote is replacing $1 with the first argument of the first script, instead of printing a literal '$1' in the second script. I believe what you want is this:

#! /bin/bash
MY_FILE=$1
MY_PATH=$2
touch "$MY_PATH"/"$MY_FILE"
echo "#! /bin/bash" > "$MY_FILE"
echo `ps -u $1 -o comm=CMD -o pid,ppid,user,uid,gid` >> "$MY_FILE"

Note that I have also added double quotes around the variable expansions, such as "$MY_FILE". This is to avoid confusion, in case the stored strings include spaces.

However, I have to say that I don't understand what you are trying to achieve here:

a) The commands you are printing to the second script don't depend on the arguments to the first script (in which case, you could simply copy the second script, if you need to duplicate it).

b) The file you have touched with touch "$MY_PATH"/"$MY_FILE" could be a completely different file to the one you have printed the other commands to, since you have not included the "$MY_PATH" variable in those calls. Perhaps that is the intended behaviour, but it seems a little strange.

1
echo 'ps -u $1 -o comm=CMD -o pid,ppid,user,uid,gid' >> $MY_FILE

In general it might be easier to use a here document for creating a script:

cat <<"EOT" >"$MY_FILE"
#! /bin/bash
ps -u $1 -o comm=CMD -o pid,ppid,user,uid,gid
EOT

Due to the quotes around EOT nothing is expanded.

4
  • Ok, this might be helpful in some other situations, but here putting the output of ps in EOT would still give me trouble with the parameters of the first script Commented Nov 3, 2017 at 20:02
  • @EscuEsculescu I don't understand your comment at all. Commented Nov 3, 2017 at 20:17
  • I still need to use "$1" (i made a mistake in my original question, where i wrote "$3"), which would expand to the first parameter of the script i'm writing myself, not to that of the script that i have to write from within my first script. Commented Nov 3, 2017 at 20:21
  • @EscuEsculescu I have understood your problem and I am quite sure that both of my suggestions do solve it. Commented Nov 3, 2017 at 20:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.