I have a command with parameters in shell. like
Command -a -b
assume a
b
are very long directory name, and they are not always the first and last parameters.
However, I need to use this command again. I use ctrl+p
to go back the command, but this time I need to reverse a
b
order.
Command -b -a
Instead of retyping them again, is there any way to fast swap them?
Thanks in advance.
Approach: Store the value of the first number into a temp variable. Store the value of the second number in the first number. Store the value of temp into the second variable.
To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.
On Unix-like operating systems, shift is a builtin command of the Bash shell. When executed, it shifts the positional parameters (such as arguments passed to a bash script) to the left, putting each parameter in a lower position.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
Yes you can use history substitution:
$ echo foo bar
foo bar
$ !:0 !:2 !:1 # previous command with second arg then first arg
echo bar foo
bar foo
$
You can use Alt + t to swap the current and the previous word.
Here are some more shortcuts.
Mind that you swap words, not parameters. If for instance you have mixed up the order grep
takes its parameters as in grep ~/Documents/myFile searchString
and want to correct that to grep searchString ~/Documents/myFile
, Alt + t won't help you.
Go for Paul's answer instead and do !:0 !:2 !:1
.
If that's too inconvenient for you to type (it is for me) you can create an alias for that in ~/.bash_alias
:
# Swap the first and the second argument of the last command
alias swapArgs='$(history -p !:0 !:2 !:1)'
Instead of swapping the args, you can easily cut and paste the last arg into a different place. Ctrl-W
will cut the last argument and Ctrl-Y
will paste it.
$ # Cursor position is shown as |
$ ls foo bar|
$ # Press <Ctrl-W> to cut the argument just before the cursor
$ ls foo |
$ # Now press <Alt-B> to move the cursor one argument back
$ ls |foo
$ # Now press <Ctrl-Y> to paste the cut argument
$ ls bar|foo
$ # Now press <space> to insert a space between the arguments
$ ls bar |foo
$ # You can safely press <enter> while the cursor is in the middle of the line
$ ls bar |foo
bar foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With