Score:7

How can I make a shell alias work immediately?

pl flag

Defining and using an alias in the same line does not seem to work:

$ alias x=ls; x
x: command not found

How can I "escape" x in the second call so that it is recognized as an alias?

Someone avatar
my flag
Add the alias in the `.bashrc` file then simply write `source ~/.bashrc` now alias is permanent
Will avatar
id flag
I’ve tried && and I’ve tried putting multiple aliases on one line (which all get assigned) … but no matter how many you put on the line, it won’t execute the first (or any) in the same line - it’s very interesting!
hr flag
See [Run alias after creation](https://unix.stackexchange.com/a/389974)
bers avatar
pl flag
@Algnis `source ~/.bashrc; x` still won't work.
Score:11
us flag

You can't (in the usual ways). See the Bash manual's section on Aliases (emphasis mine):

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input, and all lines that make up a compound command, before executing any of the commands on that line or the compound command. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. [...] To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.

You can work around it by forcing a re-parsing using eval:

$ alias x=date; eval x
Fri Nov 12 18:20:54 JST 2021
bers avatar
pl flag
`eval` is what I had been looking for! (I had tried `exec`, but `eval` hadn't crossed my mind before.) Thanks!
bac0n avatar
cn flag
+1 `shopt -s extglob; eval echo '!(file)'`
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.