1

First, disclaimer: I am very new at this.

I am trying to write a simple bash script for an assignment. I need to print the output of date, finger, and uptime to stdout, and to a file. From what I'm reading, the failure to exit seems to be because the processes are running in a subshell, but from the reading, I don't really understand how to do it. I found that using a pipe and input redirection via tee gives me the result I want, but it will not exit. Besides a pipe, and especially typing: | tee Time_Script_Output.txt on each line seems very inefficient, and I'm looking for a cleaner way to write the script.

code:

#! /bin/bash

bash 
/bin/date | tee Time_Script_Output.txt &
/usr/bin/finger | tee Time_Script_Output.txt &
/usr/bin/uptime | tee Time_Script_Output.txt 

exit

Thanks!, Nick Kavanagh

3
  • 3
    why are you running bash on the script? the script executes bash and stays in there never proceeding to your following commands. Commented Mar 17, 2015 at 17:41
  • Update, I figured it out. code: #! /bin/bash { /bin/date & /usr/bin/finger & /usr/bin/uptime & } | tee Time_Script_Output.txt exit Commented Mar 17, 2015 at 17:51
  • Welcome to Stackoverflow! +1 for including a small, complete, self-contained code sample! This makes it very easy to see what the problem is, both to answer the question now, and for future readers to relate to it. Commented Mar 17, 2015 at 17:51

1 Answer 1

2

That first bash line is incorrect. Assuming you are running this script by hand (bash script.sh) you are entering a new bash session each time the script runs. See the output from echo $SHLVL to see how deep you've gone (also the output from ps faxww). Remove that line.

You likely also don't want to be running the first two pipelines in the background you want the commands to run and the output to be written before the next command runs or you may get ordering problems in the output.

You also don't need the explicit exit at the end. The script will exit when it hits the end automatically.

You can use {} grouping to use the pipe just once:

#!/bin/bash

{
/bin/date
/usr/bin/finger
/usr/bin/uptime
} | tee Time_Script_Output.txt 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Etan, that was exactly what I ended up with. Glad to know it's an accepted way. Also kinda glad I figured it out myself, too. Lol.
It's funny, the text I'm using to teach myself gave me that assignment at the end of chapter 2, then explained brace expansion in chapter 3.
This isn't brace expansion. This is a command list. Brace expansion is echo {a,b,c}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.