-2

I created the file test.sh which contains ls -ltr & jobs command. When I run it, it gives me the output of ls -ltr, but for jobs command it doesn't give me anything, not even an error.4

Whats wrong?

michaelbn
  • 7,393
  • 3
  • 33
  • 46
  • 1
    Use `&&` instead of `&`. – Vadim Landa Jul 26 '15 at 06:04
  • 1
    @Vadim, `&` is perfectly valid for `bash`, it's the "run in background" statement terminator, similar to `;` but without waiting. In fact, it may be the OP is expecting the `jobs` to actually show the `ls` running in parallel. – paxdiablo Jul 26 '15 at 06:13
  • In programming, details are very important. To get a good answer, you need to show us what your script actually looks like. – John1024 Jul 26 '15 at 06:16

1 Answers1

1

jobs is an interactive command -- it is not meant to be used from scripts, and doesn't do anything useful in a script (but it could plausibly do something useful in a shell function called from an interactive session; so disabling it in code isn't really appropriate, either).

To keep track of background jobs, collect their PID:s when you start them.

ls -ltr &
pid=$!
printf 'pid: %s' "$pid"
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • As an aside, [`ls` should usually not be called from scripts](http://mywiki.wooledge.org/ParsingLs), either; but I understand it's used as a simple example placeholder here. – tripleee Jul 26 '15 at 07:01
  • See also http://stackoverflow.com/questions/690266/why-cant-i-use-job-control-in-a-bash-script – tripleee Jul 26 '15 at 07:07