bash: unable to set and use alias in the same line

后端 未结 2 966
庸人自扰
庸人自扰 2020-12-20 14:59

I would expect the second line to say foo instead of command not found:

$ alias foo=\"echo bac\" ; foo;
-bash: foo: command not fou         


        
2条回答
  •  一整个雨季
    2020-12-20 15:53

    To set and use alias in the same line in bash, you can use:

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

    (credits: Hauke Laging's workaround + Kusalananda's workaround).


    Explanation of the command:

    • Since "an alias definition appearing on the same line as another command does not take effect until the next line of input is read" according to the bash manual as Tom Fenech's pointed out, we use eval and place a new line between the alias definition and its use.
    • From Kusalananda's workaround:

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

提交回复
热议问题