
最新のMac OSを実行してzshellを使用していますが、シェルスクリプトの作成に問題があります。私の仕事のほとんどはコマンドラインを介して行われ、すべての入力コマンドと出力を自動的に保存して記録するbashスクリプトがあります。
最も明確な選択は、通常、次のようにコマンドラインで実行されるbash "script"コマンドです。
script -a <filename>.txt
log.sh
次の内容でシェルスクリプトを作成しました。
#! /bin/sh
echo "Welcome to the jungle."
# get date
now=$(date +%Y_%m_%d)
# create filename
fname='log_'$now'.txt'
# file save location
floc=~/path/to/directory/$fname
# start script
script -a -q $floc
これにより、ファイル名が今日の日付で指定されたディレクトリに保存されるスクリプトが起動します。しかし、ファイルの内容を書くこと以外はうまくいきます。予想された計画されたテキスト入力/出力の代わりにファイルを読みにくくするANSI文字と思われる内容を得ました。
私のコマンドラインは次のとおりです。
~$ bash log.sh
Welcome to the jungle.
~$ echo "Hello world"
Hello world
~$ exit
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
そして、ログファイルに書き込まれる方法は次のとおりです。
[1m[7m%[27m[1m[0m
]7;file://<myname>/Users/<myusername>
[0m[27m[24m[J[36m<myusername> [38;5;246m~[39m$ [K[?2004heecho "Hello world! "[?2004l
Hello world
[1m[7m%[27m[1m[0m
]7;file://<myname>/Users/<myusername>
[0m[27m[24m[J[36m<myusername> [38;5;246m~[39m$ [K[?2004heexit[?2004l
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
コマンドを使用してcat
テキストを表示したり、Perlスクリプトを使用してキーを削除したりするなど、ファイルを作成した後にANSIキーを処理する方法がいくつかありますが、大きなファイルを表示しようcat
とすると迷惑です。コマンドを使用するのも面倒で、ファイルを手動でクリーンアップする必要があるのも面倒です。コマンドラインの入力と出力を記録する方法はありますか?いいえANSIキー?
ありがとうございます!
答え1
簡単な方法はを使用することですless -R
。これはまさにあなたが要求したものではありませんが、とにかく役に立ちます。
答え2
これはうまくいくようです:
#!/usr/bin/env zsh
{
# Create a named pipe, using a temp file name.
mkfifo -m 600 ${fifo::=$(mktemp -u)}
logFile="~/logs/log-$(date +%F-%H-%M-%S).txt"
print "Logging to $logFile"
# Launch the filter in the background (&), so it will
# run in parallel with the script utility.
# This will read from the named pipe, remove the ansi
# color escapes, and write the result to the log.
# (perl source: https://superuser.com/a/1388860).
perl -pe 's/\e\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]//g;
s/\e[PX^_].*?\e\\//g;
s/\e\][^\a]*(?:\a|\e\\)//g;
s/\e[\[\]A-Z\\^_@]//g;' \
< $fifo > ${~logFile} &
# Get the process id of the background process.
fifoPid=$!
# Launch the script utility, capturing data from the
# interactive shell. -F ensures writes are immediately
# available in other processes.
script -q -F $fifo
# script -q -F $fifo bash
# The background process will end when the script
# utility closes its handle to the fifo, i.e. when the
# shell launched by 'script' exits. But it may not exit
# immediately, so it could be running when we get to
# this point. This will bring it to the foreground, just
# in case some other actions follow this script.
wait $fifoPid
} always {
# cleanup temp fifo.
if [[ -p $fifo ]] rm $fifo
}
これは名前付きパイプscript
リアルタイムで出力をフィルタリングします。起動したシェルから後処理でクリーンアップフィルタを実行することもできますが、script
それほど面白くありません。