I am trying to make a bash shell script that launches some jobs on a queuing system. After a job is launched, the launch command prints the job-id to the stdout, which I would like to ‘trap’ and then use in the next command. The job-id digits are the only digits in the stdout message.
#!/bin/bash ./some_function >>> this is some stdout text and the job number is 1234...
and then I would like to get to:
echo $job_id >>> 1234
My current method is using a tee command to pipe the original command’s stdout to a tmp.txt
file and then making the variable by grepping that file with a regex filter…something like:
echo 'pretend this is some dummy output from a function 1234' 2>&1 | tee tmp.txt job_id=`cat tmp.txt | grep -o '[0-9]'` echo $job_id >>> pretend this is some dummy output from a function 1234 >>> 1 2 3 4
…but I get the feeling this is not really the most elegant or ‘standard’ way of doing this. What is the better way to do this?
And for bonus points, how do I remove the spaces from the grep+regex output?
Advertisement
Answer
You can use grep -o
when you call your script:
jobid=$(echo 'pretend this is some dummy output from a function 1234' 2>&1 | tee tmp.txt | grep -Eo '[0-9]+$') echo "$jobid" 1234