Bash

bash 防止 printf 中斷另一個 printf

  • September 7, 2015

我有以下測試腳本。

#!/bin/bash

function foo {
 printf "Test line break: $1\nafter line break\n\n"
}

for VARIABLE in {1..30}
do
 foo $VARIABLE &
done
wait

現在我多次執行腳本,有時輸出如下所示:

Test line break: 15
Test line break: 14
after line break: 14
after line break: 15


Test line break: 16
after line break: 16

而不是預期的:

Test line break: 15
after line break: 15

Test line break: 14
after line break: 14

Test line break: 16
after line break: 16

如何防止 printf “中斷”另一個 printf,但仍在後台執行它?

對我來說,問題似乎是 printf 中的“\n”。

事實上,你需要一個互斥鎖:

每個子 shell 將同時訪問相同/dev/stdout的父 shell,因此即使在同一個函式內部也無法確保順序。為了確保它,您需要一個強制互斥的鎖,即:所有其他程序/dev/stdout在鎖被釋放之前不會開始寫入。

#!/bin/bash

function foo {
lockdir=/tmp/myscript.lock
mkdir "$lockdir" 2>/dev/null
while [ $? -ne 0 ]; do mkdir "$lockdir" 2>/dev/null; done
printf "Test line break: $1\nafter line break: $1\n\n"
rm -rf $lockdir
}

for VARIABLE in {1..30}
do
 foo $VARIABLE &
done
wait

這將給出這樣的結果:

$ bash plop1 2>/dev/null
Test line break: 5
after line break: 5

Test line break: 3
after line break: 3

Test line break: 11
after line break: 11

Test line break: 23
after line break: 23

Test line break: 14
after line break: 14

Test line break: 17
after line break: 17

Test line break: 24
after line break: 24

Test line break: 21
after line break: 21

Test line break: 27
after line break: 27

Test line break: 6
after line break: 6

Test line break: 2
after line break: 2

Test line break: 9
after line break: 9

Test line break: 26
after line break: 26

Test line break: 29
after line break: 29

Test line break: 20
after line break: 20

Test line break: 1
after line break: 1

Test line break: 12
after line break: 12

Test line break: 4
after line break: 4

Test line break: 13
after line break: 13

Test line break: 10
after line break: 10

Test line break: 15
after line break: 15

Test line break: 28
after line break: 28

Test line break: 25
after line break: 25

Test line break: 19
after line break: 19

Test line break: 18
after line break: 18

Test line break: 8
after line break: 8

Test line break: 7
after line break: 7

Test line break: 16
after line break: 16

Test line break: 22
after line break: 22

Test line break: 30
after line break: 30

引用自:https://unix.stackexchange.com/questions/228040