3

Since I need to set and use alias in the same line in bash, I would like to use Hauke Laging's workaround:

eval 'alias df5=df
df5 -h'

(I took df and df5 for the sake of the example. I am aware that in this specific example one could replace the entire eval command by df -h.)

However I would prefer to write this command into one line.

How can I write an eval command containing a new line into one line?


I unsuccessfully tried the following one-line commands:

  • eval 'alias df5=df\ndf5 -h'. Error -bash: alias: -h: not found
  • alias df5=df ; df5. Error: No command 'df5' found
  • alias df5=df && df5 (suggested by Cyrus). Error: No command 'df5' found
0

2 Answers 2

4

Since you're using bash:

eval $'alias df5=df\ndf5 -h'

The $'...' is a "C string", and bash would expand the \n within it to a literal newline before passing it to eval.

Care must be taken as other backslash sequences would possibly also be expanded. See the second half of the QUOTING section in the bash manual.

2
  • Works great, thanks! Commented May 9, 2020 at 21:00
  • @FranckDernoncourt If one answer was the "most helpful" you should accept it, that is one way to thank helpful answers and make it more visible. Thanks.
    – user232326
    Commented May 10, 2020 at 3:58
1

There are several solutions, but all should hinge on the idea of writing a newline with other characters. The first possible solution, a portable one (very old) is to get a newline inside a variable:

nl='
'
eval 'alias df5=df'"$nl"'df5 -h'

The assignment of an explicit newline to a var may look odd, if that is the case, we can use:

  • Ansi-C quoting (ksh,bash,zsh):

    nl=$'\n'
    
  • printf (most shells):

    eval "$(printf "nl='\n'")"
    

But then, those two ideas might be used directly to define the alias:

eval $'alias df5=df\ndf5 -h'
eval "$(printf "alias 'df5=df\ndf5 -h'")"

But, of course, you can forget the newline, and define the alias as:

alias df5=df && df -h

But I am not sure if that would fit your use case. :-)

2
  • Thanks for the alternatives! Does eval "$(printf "alias 'df5=df\ndf5 -h'")" work on your side? It doesn't print anything in my bash. Commented May 10, 2020 at 1:11
  • @FranckDernoncourt It would not print anything as it just defines an alias. Checking with alias df5 will confirm that the alias has been defined.
    – Kusalananda
    Commented Nov 17, 2020 at 11:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .