how to use ctrl-D in a shell script
I have a bash shell script that requires ctrl-D to break out of the terminal.can anyone tell me how to use it in the shell script
example
ssh host last --->displays the list of users who were logged on to that host
I have different hosts the output is appended to one final and when I'm executing this particular shell script along with other 开发者_Go百科series of commands, i'm using ctrl-D to see the output
suppose my shell script is myscript.sh to execute myscript.sh
./myscript.sh
ctl-D
connection to host closed
output is displayed
Instead, I want to use ctrl-D in my script file
There is no way to do this directly. Use a heredoc to feed stdin instead.
./someprog.sh << EOF
something here
EOF
You could try exec <&-
&-
is used to close a file descriptor (ps:everything in linux is a kind of file...)
<&-
is closing file descriptor 0 = stdin - can also be written as 0<&-
If you open a normal terminal in your linux machine and type exec <&-
you will see your terminal to close/dissapear like if you press ^D.
PS1: Similarly, exec >&-
closes stdout
PS2: If you close stdin with exec <&-
you can re-open to continue your script with something like exec </dev/tty
To detect Ctrl-D in scripts and run custom logic on it you can read input char by char and check if char key code corresponds to Ctrl-D.
Here is a code example:
IFS=
while true; do
read -n 1 key
line=$line$key
printf -v key_code "%d" "'$key"
if [ $key_code -eq 4 ]; then
echo "Ctrl-D pressed!"
fi
if [ "$key" = '' ]; then
echo "Line was $line"
line=
fi
done
Use this
read Input
#When ^D is used, read ends up with the exit code "1"
if [[ $? == 1 ]]
then
echo "[Ctrl+D] is captured"
fi
#! /bin/sh
echo 'Enter one line at a time'
echo 'Press CTRL+D to finish'
cat >test.out
echo 'OK'
Why don't you tell last
how many lines you want to see? Then you won't have to interrupt it with a Ctrl+D. For example, to see 10 lines use:
ssh hostname "last -10"
精彩评论