简体   繁体   中英

Can Bash History Expansion be used to reference something in the same command?

Bash has this feature called history expansion where you can use shortcuts that expand to things you've typed previously into bash.

Example: !! - expands into previous command !! - expands into previous command

$> rm -f /var/log/access.log
rm: /var/log/access.log: Permission Denied
$> sudo !!
sudo rm -f /var/log/access.log
$> echo "i am teh hax"

Another: !$ - expands into last arg of previous command

$> echo "no one was here" > access.log
$> cp !$ /var/log/
cp access.log /var/log/

Does bash, or some other shell, have the ability to use substitution shortcuts within the command itself?

Something like

$> cp httpd.conf !$.bak
cp httpd.conf httpd.conf.bak
$> echo "SABOTEUR!!!" > httpd.conf

I need to up my 1980's cyberpunk skills. Please Help.

by within the command itself, do you mean you want to refer to httpd.conf ?

Then this is your solution in superuser

Using bash history expansion :

mv path/to/oldfile !#:1:h/newfile

where !#:1:h means: from the line you're currently typing ( !# ), take the first word ( :1 ), then take only the path component ( :h -- the head) from it.

The answer by justhalf is what you want.

But for your requirement, there is one more hack/misuse available.

sed -i.bak '' /path/to/file

eg

sed -i.bak '' httpd.conf 

It will copy your file to another file with .bak appended.

Advantage: /path/to/file can contain wildcards/globs, or you can directly give a white-space separated list of files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM