0

Every time to type script.sh > log.txt 2>&1 & I feel tired. I've tried making alias of "alias bg21=2>&1 &" but it doesn't work properly.

For example, if I do:

echo 5 > test.log bg21

I would see in test.log file has:

5 bg21
1
  • 1
    Instead of an alias or wrapper which will only make things more obtuse, consider using some key binding, eg. bind '"\C-_": "2>&1 &"' in bash (change the C-_ = C-7, C-&, C-/ if you're already used to use them for "undo") – mosvy Feb 18 '20 at 21:43
4

You can define a function:

function bkg { 2>&1 "$@" & }

And then use:

bkg script.sh arg1 arg2 ... >log.txt
3
  • @mosvy It does for me... – xenoid Feb 18 '20 at 22:07
  • Yes it does, sorry. – mosvy Feb 18 '20 at 22:13
  • Thanks! it works. However I have new problem in doing this, that the background process will now show as bash [1] "$@" 2>&1 which I cannot tell any useful information what's running there. Not sure if we can get avoid that. – jtcloud Feb 19 '20 at 15:34
0

If your goal is to redirect both stdout and stderr to a file, you can simply write

echo 5 &> test.log &

This is the shortest way I know to accomplish what you want here.

2
  • 2
    that's a BASH-ONLY deprecated feature, which in all the other shells will be parsed differently, namely as echo 5 & followed by >test.log & (the test.log file will be truncated, and nothing will be written to it). – mosvy Feb 18 '20 at 21:23
  • 1
    It works on my bash environment well. It looks cleaner and avoided the problem of hidden process descriptions in background that @xenoid 's solution introduced. – jtcloud Feb 19 '20 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.