0

I can do this as:

if [[ "$is_to_rename" == true ]]
then
    printf "path %s\n" "a" >> $logger
else
    printf "path %s\n" "a"
fi

But would be nice to reduce the duplicated code printf "path %s\n" "a", so tried the following small code:

#!/bin/bash
is_to_rename=true
printf "path %s\\n" "a" if [[ "$is_to_rename" == true ]]; then >> $logger; fi

But throws the error:

./fixer.sh
./fixer.sh: line 66: syntax error near unexpected token `then'
./fixer.sh: line 66: `        printf "path %s\n" "a" if [[ "$is_to_rename" == true ]]; then >> $logger; fi'

enter image description here

It is possible not to keep repeating the code printf "path %s\n" "a"? [And do it in one line? (just for fun)]

Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
  • 1
    `if [[ "$is_to_rename" == true ]]; then exec >> "$logger"; fi` redirects all standard output to the file name by `"$logger"`. This is often what you want. If you might need to echo to standard output sometime later in the script, you have to work harder, but it is still far from impossible. Note that `{ cmd1; cmd2; cmd3; } >> '$logger"` redirects the output of the three commands to the file; it is used for grouping I/O redirection. And the `;` after the last command is necessary unless the `}` is on a line after the command. – Jonathan Leffler Aug 06 '17 at 14:18
  • 2
    `if ...; then logger="filename"; else logger=/dev/stdout; fi; printf ... >> "$logger"`? – Cyrus Aug 06 '17 at 14:21
  • Thanks @Cyrus, it worked fine using `if [[ "$is_to_rename" == true ]]; then logger="filename"; else logger=/dev/stdout; fi; printf ... >> "$logger"` – Evandro Coan Aug 06 '17 at 16:36

0 Answers0