Leonald
Leonald

Reputation: 81

How to pass the output from one command as value of argument of the next command

I want to pass the result of a command as a value of an argument of the next command. I know there is xargs and pipe | but those don't really help.

I want to run the command tail -f --pid=$REMOTE_PID logs where REMOTE_PID is the PID of a program which is running on a remote server. It writes digits from 1 to 30 in a log file and sleep(1). So I want to display simultaneously the digits coming from the log file on the local machine. All this is done in a script, not manually !!

Here is what I have done so far but can't get the correct PID. In the first command, I put the & to release the shell, so that I can run the next command

ssh user@host 'nohup sh showdigits.sh' &
ssh user@host 'PID=`pgrep -f showdigits.sh` && tail --pid=$PID -f logs'

These commands work but I get several PIDs before gitting the right one:

tail: cannot open '8087' for reading: No such file or directory
tail: cannot open '8109' for reading: No such file or directory
==> logs <==
1
2
3
...

I tried another code :

ssh user@host 'nohup sh showdigits.sh' & 
ssh user@host "ps -ef | awk '/[s]howdigits.sh/{print $2}' > pid && tail --pid=`cat pid` -f logs"

I get this error :
cat: pid: No such file or directory
tail: : invalid PID

I want to have the only one PID of the script showdigits.sh and pass it to tail. Maybe is there a simpler solution ?

Thank you

Upvotes: 0

Views: 217

Answers (2)

that other guy
that other guy

Reputation: 123460

Your strategy is:

  1. Start a process
  2. Disconnect and forget about it
  3. Reconnect and try to find it
  4. Follow it

You can simplify it by dropping step 2 and 3 entirely:

ssh user@host '
  nohup sh showdigits.sh &
  tail --pid=$! -f logs
'

(NB: using sh to run a script is a worst practice)

Upvotes: 1

alecxs
alecxs

Reputation: 731

your grep is matching more than 1 result. first match is assigned to --pid= and others are interpreted as file names.
you have to pass it through head (or tail) before processing (depending on which pid you want)
PID=$(pgrep -f showdigits.sh | head -n1)

Upvotes: 0

Related Questions