How can I check from my Swift script whether or not I am outputting to a terminal?
例如,在bash或zsh脚本中,可以使用-t 1
条件表达式来判断文件描述符1(stdout)是否打开并与终端设备关联:
if [[ -t 1 ]]; then
echo "\e[31m"HELLO"\e[0m" # colorize output
else
echo hello
fi
请注意,当脚本在交互式shell中运行,而不是通过管道传输到其他程序时,格式会有所不同:
./script
↪︎ HELLO
./script | tee
↪︎ hello
What is the equivalent in Swift?
#!/usr/bin/env swift
if ❓ {
print("\u{001B}[31m" + "HELLO" + "\u{001B}[0m")
} else {
print("hello")
}