Fet32
Fet32

Reputation: 35

BASH: special parameter for the last command, not parameter, executed

I am looking for a workaround for processes with a long duration. There is the special parameter $_ containing the last parameter of the last command. Well I am asking you for something vice versa.

For example:

/etc/init.d/service stop; /etc/init.d/service start

.. could be easier if there is a parameter/variable containing the last binary/script called. Let's define it as $. and we get this:

/etc/init.d/service stop; $. start

Do you have any Idea how to get this? I found this Thread on SO But I only get output like this: printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"

But the var $BASH_COMMAND is working well:

# echo $BASH_COMMAND
echo $BASH_COMMAND

# echo $BASH_VERSION
4.1.2(1)-release

Any help is very appreciated! Thank you, Florian

Upvotes: 1

Views: 228

Answers (2)

Darren Douglas
Darren Douglas

Reputation: 196

If the primary problem is the duration of the first process, and you know what the next process will be, you can simply issue a wait command against the first process and follow it with the second.

Example with backgrounded process:

./longprocess &
wait ${!}; ./nextprocess # ${!} simply pulls the PID of the last bg process

Example with manual PID entry:

./longprocess
# determine PID of longprocess
wait [PID]; ./nextprocess 

Or, if it is always start|stop of init scripts, could make a custom script like below.

#/bin/bash
#wrapperscript.sh
BASESCRIPT=${1}
./$BASESCRIPT stop
./$BASESCRIPT start

Since the commands are wrapped in a shellscript, the default behavior will be for the shell to wait for each command to complete before moving on to the next. So, execution would look like:

./wrapperscript.sh /etc/init.d/service

Upvotes: 0

Raad
Raad

Reputation: 4648

You can re-execute the last command by using:

!!

however, this won't help with what you want to do, so you could try using the "search and replace on last command" shortcut:

^<text to search for>^<text to replace with>^

so your problem could be solved using:

/etc/init.d/service stop; ^stop^start^

NOTE: This will only replace the first instance of the search text.

Also, see the comments below by more experienced peeps, for other examples and useful sources.

Upvotes: 1

Related Questions