5

I created a bash script that installed some applications and wrote a .conf file. I wanted my bash script to create the file for me so I could just run the file and it set it all up. was there a better way of going about it than this or did I do it in the best way possible. just wondering what other options I had.

Note: the file does work

if [ ! -e ~/.conf/file/path ]; then
   touch ~/.conf/file/path
   echo "
    long
    conf
    list
    here
    ..." >> ~/.conf/file/path
fi

3 Answers3

7

Just do echo "text" >> /path/to/file if the file doesn't exist.

The lovely thing about text redirection and appending is that if your output is a file path, and the file doesn't already exist, it'll create the file, regardless of if > or >> is used. No need to touch the file at all, typically. (Though, if you are sure the file does not exist, just use > instead of >>; >> is to append to a file, but if the file doesn't exist, well...)

Thomas Ward
  • 74,764
2

As far as your script goes, you can use > redirection to file. You're asking if the file doesn't exist (which should better be expressed as if ! [ -e ~/.conf/file/path ];), therefore there is no need to use append operator in this particular case (even though it works alright).

As for printing long multiline configuration into the file, Panther already hinted at use of here docs in his comment under Thomas's answer. This is a frequent technique I personally use for writing "help message" or options information in my scripts

You could easily do something like this:

bash-4.3$ cat <<EOF > out.txt
parameter1="value 1"
parameter2="value 2"
EOF
bash-4.3$ cat out.txt
parameter1="value 1"
parameter2="value 2"
bash-4.3$ 

Or alternatively create a specific function, write_config() to make your script more idiomatic, so to speak:

#!/usr/bin/env bash
# note usage of $HOME variable instead of ~
my_config="$HOME/my_conf_file.txt"
# declare all functions at the top
config_exists()[[ -e "$my_config" ]]

write_config(){ cat > "$my_config" <<EOF parameter1="value 1" parameter2="varlue 2" EOF }

if ! config_exists; then echo "config doesn't exist" write_config fi

BBQ
  • 13
Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
0

If the "long conf list" is so long that it impedes the readability of your shell script, why not just place it into a separate file that accompanies the script? Then all your need to do in the shell script is copy that file to the destination.

if [ ! -e ~/.conf/file/path ]; then
   cp /path/to/mytemplate ~/.conf/file/path
fi
thomasrutter
  • 36,774