Can't reference parameter in Bash

I want to put TextA at the beginning of TextB with

cat TextA A TextB

      

The problem is that I don't know how to refer to the first and second parameters: TextA and TextB in the following script called A:

  #!/bin/bash

  cat TextA > m1
  cat TextB > m2
  cat m1 m2 > TextB

      

where m1 and m2 are temporary files.

How can you link to two files in a shell script?

+1


a source to share


6 answers


You can use the $0

, $1

, $2

, and so on to refer to variables in the script.

$0

- this is the name of the script itself $1

- the first parameter $2

- the second parameter, etc.

For example, if you have this command:



a A1 A2

      

Then inside a

you get:

$0 = a
$1 = A1
$2 = A2

      

+4


a source


In a bash script, the first parameter is $ 1, the second is $ 2, etc.

If you want to use the default, for example the third parameter you can use:



var=${3:-"default"}

      

+3


a source


you can just use append (→)

cat TextB >> TextA

      

the result is that TextA precedes TextB in TextA

+2


a source


I would do the following:

#!/bin/bash

if [ $# -ne 2 ]
then
  echo "Prepend file with copyright notice"
  echo "Usage: `basename $0` <copyright-file> <mainfile>"
  exit 1
fi

copyright=$1
mainfile=$2

cat $mainfile > /tmp/m.$$
cat $copyright /tmp/m.$$ > $mainfile

#cleanup temporary files
rm /tmp/m.$$ /tmp/m2.$$

      

+1


a source


I'm surprised no one is suggesting the following result

cat TextA TextB | tee > TextB

      

This way, you can avoid the problems of creating a temporary file.

+1


a source


It looks like you can just do the following:


TextA="text a"
TextB="text b"
echo "$TextA $TextB" > file1

      

Or use the append (→) operator.

0


a source







All Articles