date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,427,416,989,000
I've been trying to figure out why I get a literal end-of-transmission character (EOT, ASCII code 4) in my variable if I read Ctrl+D with read -N 1 in bash and ksh93. I'm aware of the distinction between the end-of-transmission character and the end-of-file condition, and I know what Ctrl+D does when using read withou...
It might be more helpful if the doc pointed out that there's no such thing as an ASCII EOF, that the ASCII semantics for ^D is EOT, which is what the terminal driver supplies in canonical mode: it ends the current transmission, the read. Programs interpret a 0-length read as EOF, because that's what EOF looks like on...
How to signal end-of-input to "read -N"?
1,427,416,989,000
Of course you can do this sort of thing, read var; if [[ $var = 'y' ]]; then echo "Yes"; fi But is there any way to skip the first step and do something a little more like this, (ideally without needing a subshell): if [[ $(read var) = 'y' ]]; then echo "Yes"; fi Of course the above doesn't work unless you add echo...
How about using a function to do what you need: user_input () { read var echo $var } if [ "$(user_input)" = 'y' ]; then echo "Yes"; fi At the top I define a function called user_input, which will read the value in, and then echo it out. Then the if statement is able to take that value and check if it is 'y'....
Succinct way to respond to user input?
1,427,416,989,000
I am trying to echo the variables $f1, $f2, ... , outside of the while loop shown below. From what I understand, the scope of the variable is not correct. Therefore I tried a few of the workarounds as shown in the Bash FAQ: while IFS=: read -r f1 f2 f3 f4 f5 f6 f7; do echo "Username: $f1. Home directory:$f6" done</e...
In your link, the variable used outside (linecount) is not defined as a "loop" variable. It's just modified (incremented) inside the body loop, but not in the "while" statement. This is because when the "read -r f1 f2..." part is called, it reset (prepare) the variables used (f1 ..f7), wait for an input line and assig...
Preserve read statement's last variable assignments outside of "while" loop
1,427,416,989,000
I am trying to write a BASH function that will do x if program a or b finish. example: echomessage() { echo "here's your message" if [[sleep 3 || read -p "$*"]] then clear fi } In this scenario: a = 'sleep 3' which is supposed to run x after 3 seconds b = 'read -p "$*"' which is supposed to run x upon providing an...
read has a parameter for timeout, you can use: read -t 3 answer If you want read to wait for a single character (whole line + Enter is default), you can limit input to 1 char: read -t 3 -n 1 answer After proper input, return value will be 0, so you can check for it like this: if [ $? == 0 ]; then echo "Your answ...
BASH function to read user input OR interrupt on timeout
1,427,416,989,000
I have a file foo.txt test qwe asd xca asdfarrf sxcad asdfa sdca dac dacqa ea sdcv asgfa sdcv ewq qwe a df fa vas fg fasdf eqw qwe aefawasd adfae asdfwe asdf era fbn tsgnjd nuydid hyhnydf gby asfga dsg eqw qwe rtargt raga adfgasgaa asgarhsdtj shyjuysy sdgh jstht ewq sdtjstsa sdghysdmks aadfbgns, asfhytewat bafg q4t...
You need to make some changes to your script (in no particular order): Use IFS= before read to avoid removing leading and trailing spaces. As $line is not changed anywhere, there is no need for variable readLine. Do not use read in the middle of the loop!!. Use a Boolean variable to control printing. Make clear the s...
Read a file line by line and if condition is met continue reading till next condition [closed]
1,554,498,125,000
I'm not looking for work-arounds or solutions for the issue. I'm fine with it not working like that in bash. I just don't understand why it doesn't work. I'm looking for an in-depth answer why the following script doesn't work. All previous internet search results, including posts from unix.stackexchange.com, couldn't...
You did read from stdin with read, but what you read was the next line of standard input - namely echo "Hello $NAME". After reading that line, there was no more input and so no further commands to execute, and the script was over. There is only one standard input stream, and you're trying to use it for both code and d...
Why isn't it possible to read from `stdin` with `read` when piping a script to bash?
1,554,498,125,000
I was trying to write a shell script that idly waits for a signal in the background. Since the script doesn't take user input I thought of using read to block the script indefinitely while waiting. In bash the following code seems to work as expected, outputing "signal" every time it receives a SIGUSR1: #!/bin/bash tr...
Dash and BusyBox comply with the POSIX specification by making the signal quit read immediately. Bash doesn't, unless invoked in POSIX mode. The section on signals states When a signal for which a trap has been set is received while the shell is waiting for the completion of a utility executing a foreground command, ...
Why does sending a trapped signal cause `read` to return in POSIX shell but not in Bash?
1,554,498,125,000
I want to know which keys are pressed on my keyboard and print the information to stdout. A tool that can do this is showkey. However, if I want to pass the data of showkey to read: while read line; do echo "$line" | otherprog done <`showkey -a` OR showkey -a | while read line; do echo "$line" | otherprog done T...
Try setting showkey output to non-buffering with the stdbuf command: stdbuf -o0 showkey -a | cat - Will show the output as keys are pressed, rather than buffering a line. stdbuf can adjust the buffering of stdin, stdout and stderr, setting them to none, line buffered, or block buffered, with a choosable block size. ...
Print currently pressed keys to stdout and read them line by line
1,554,498,125,000
I'm working on a bash script that parses a tab separated file. If the file contains the word "prompt" the script should ask the user to enter a value. It appears that while reading the file, the "read" command is not able to read from standard input as the "read" is simply skipped. Does anybody have a work around fo...
The simplest way is to use /dev/tty as the read for keyboard input. For example: #!/bin/bash echo hello | while read line do echo We read the line: $line echo is this correct? read answer < /dev/tty echo You responded $answer done This breaks if you don't run this on a terminal, and wouldn't allow for input ...
bash: Prompting for user input while reading file
1,554,498,125,000
I have a bash script where I'm trying to assign a heredoc string to a variable using read, and it only works if I use read with the -d '' option, I.e. read -d '' <variable> script block #!/usr/bin/env bash function print_status() { echo echo "$1" echo } read -d '' str <<- EOF Setup nginx site-conf...
I guess the question is why read -d '' works though read -d'' doesn't. The problem doesn't have anything to do with read but is a quoting "problem". A "" / '' which is part of a string (word) simply is not recognized at all. Let the shell show you what is sees / executes: start cmd:> set -x start cmd:> echo read -d "...
How does the -d option to bash read work?
1,554,498,125,000
I'm working on a relatively new Linux Mint installation and I haven't noticed any significant issues until just now, I realised I couldn't use any command-line tools that interactively read user input. Instead of processing an enter key as I'd expect by consuming a line of input, it's printing the ^M character sequenc...
This usually happens when a program which set the terminal to raw input mode died unexpectedly and wasn't able to restore the terminal settings to their prior values. A simple stty sane should reset everything to normal. As part of making the terminal "raw", the translation of Carriage-Return (^M, \r) to Line-Feed (^J...
shell read incorrectly processes enter keypress
1,554,498,125,000
I'm trying to write a bash script that will let me save a backup code (lots of numbers) in a file. I've finished the script but it's only letting me to save 4096 digits of the code. I tried to do this: # Ask for backup code read -p "Backup code:" backupcode # Check backup code length l="${#backupcode}" m=4096 if (( l ...
There's no limit for the read command itself. But there's a limit for how much you can type on a single line in the terminal. To see this, try running the command wc -c and typing a very long line. You'll hit that same limit at 4096 bytes. To input more than the limit, either arrange to make the code multi-line with e...
Is there a limit for the read command?
1,554,498,125,000
echo " a" | while read; do echo "$REPLY"; done will output ".....a" which contains leading white space. However, echo " a" | while read line; do echo "$line"; done will output "a" with leading white space skipped (OK, because word splitting). It seems the REPLY variable has the same effect of IFS set to nul...
From read man page: Read one line from the standard input, (or from a file) and assign the word(s) to variable name(s). If no names are supplied, the line read is assigned to the variable REPLY. So, $REPLY is always the whole line, while the assigned variables are always words. It would not work otherwise e.g. if yo...
why REPLY variable in read builtin skip white space?
1,554,498,125,000
In bash, if I wanted to read, say 3, characters from a pipe, I could do: ... | read -n3 In zsh's read, the closest option seems to be -k: -k [ num ] Read only one (or num) characters. All are assigned to the first name, without word splitting. This flag is ignored when -q is present. Input is read from the termi...
It's a bit weird, but it is documented: -k [num] (…) Input is read from the terminal unless one of -u or -p is present. The reason your first attempt hangs there is that it's reading from the terminal. Typing three characters on the terminal does unblock it. To read from standard input when you're asking for a limit...
What's the zsh way to read n characters from stdin?
1,554,498,125,000
read -r -p "put an option: " option echo $option this works but shellcheck gives me: In POSIX sh, read -p is undefined. How to get user input with a prompt into a variable in a posix compliant way?
You could use read without -p: printf "put an option: " >&2 read -r option printf '%s\n' "$option"
how to get user input with a prompt into a variable in a posix compliant way
1,554,498,125,000
While I was reading this answer, the author used this command to put the result of a heredoc to a variable: read -r -d '' VAR <<'EOF' abc'asdf" $(dont-execute-this) foo"bar"'' EOF I'm a little confused about the -d option. From the help text for the read command: -d delim continue until the first character of DELIM i...
Mostly, it means what it says, e.g.: $ read -d . var; echo; echo "read: '$var'" foo. read: 'foo' The reading ends immediately at the ., I didn't hit enter there. But read -d '' is a bit of a special case, the online reference manual says: -d delim The first character of delim is used to terminate the input line, ra...
What does the "-d" option of the "read" shell command do when I use it with an empty string as argument?
1,554,498,125,000
I can do this in bash: while read -n1 -r -p "choose [y]es|[n]o" do if [[ $REPLY == q ]]; then break; else #whatever fi done which works but seems a bit redundant, can i do something like this instead? while [[ `read -n1 -r -p "choose [y]es|[n]o"` != q ]] do #whatever done
You can't use the return code of read (it's zero if it gets valid, nonempty input), and you can't use its output (read doesn't print anything). But you can put multiple commands in the condition part of a while loop. The condition of a while loop can be as complex a command as you like. while IFS= read -n1 -r -p "choo...
How to use user input as a while loop condition
1,554,498,125,000
In a remote CentOS with Bash 5.0.17(1) where I am the only user via SSH I have executed read web_application_root with: $HOME/www or with: ${HOME}/www or with: "${HOME}"/www or with: "${HOME}/www" Aiming to get an output with an expanded (environment) variable such as MY_USER_HOME_DIRECTORY/www. While ls -la $HOME...
Variables are not expanded when passed to read. If you want to expand the $VARs or ${VAR}s where VAR denotes the name of an existing environment variable (limited to those whose name starts with an ASCII letter or underscore and followed by ASCII alnums or underscores) and leave all the other word expansions ($non_exp...
How to expand variables inside read?
1,554,498,125,000
Consider the following shell script echo foo; read; echo bar Running bash my_script outputs 'foo', waits for the return key and outputs 'bar'. While this works fine running it that way, it doesn't work anymore if piped to /bin/bash: $ echo 'echo foo;read;echo bar'|bash directly outputs 'foo' and 'bar' without waitin...
This is really easy, actually, First, you need to set aside your stdin in some remembered descriptor: exec 9<&0 There. You've made a copy. Now, let's pipe our commands at our shell. echo 'echo foo; read <&9; echo bar' | bash ...well, that was easy. Of course, we're not really done yet. We should clean up. exec 9<&- ...
Wait for key in shell script that may get piped to /bin/bash
1,554,498,125,000
I have some php scripts which I run in sequential order like: php index.php import file1 --offline && php index.php import file2 --deleteUnused && php index.php import file3 Now I have newly discovered the parallel command and I tried something like that: parallel -j 3 -- "php index.php import file1 --offline" "php i...
Create myFileWithCommands.txt: php index.php import file1 --offline php index.php import file2 --deleteUnused php index.php import file3 Then run parallel like this: parallel -j 3 -- < myFileWithCommands.txt
How to read commands from file?
1,554,498,125,000
I am using the following counter functionality in a script: for ((i=1; i <= 100; i++ )); do printf "\r%s - %s" "$i" $(( 100 - i )) sleep 0.25 done is there a way I can pause and resume the counter with keyboard input? (preferably with the same key - lets say with space)
Use read with a timeout -t and set a variable based on its output. #!/bin/bash running=true for ((i=1; i <= 100; i++ )); do if [[ "$running" == "true" ]]; then printf "\r%s - %s" "$i" $(( 100 - i )) fi if read -sn 1 -t 0.25; then if [[ "$running" == "true" ]]; then running=fa...
Bash - pause and resume a script (for-loop) with certain key
1,554,498,125,000
So here's my deal: working in BASH, I have already built out a function which works just fine that accepts an array or any number of parameters, and spits out an interactive menu, navigable by arrows up or down, and concluding with the user hitting enter, having highlighted the menu item they desire (the output of whi...
You can read for -n 1, and read the following two if the first one is \033 and react accordingly. Otherwise, handle the number directly. #!/bin/bash read -n1 c case "$c" in (1) echo One. ;; (2) echo Two. ;; ($'\033') read -t.001 -n2 r case "$r" in ('[A') echo Up. ;; ...
BASH question: using read, can I capture a single char OR arrow key (on keyup)
1,554,498,125,000
I want to grep some line from a log file with an input from another file. I'm using this small command to do that: while read line; do grep "$line" service.log; done < input_strings.txt > result.txt input_strings.txt has like 50 000 strings (one per line). For every of this string I'm currently searching the hu...
If you want to get the matches then you don't need to be using a loop at all. It would be much faster to just use a single grep command: grep -Ff input_strings service.log > results.txt That said, if you want to do literally what you stated in your question, then you could use a variable to keep track of the line on ...
read file line by line and remember the last position in file
1,554,498,125,000
I have some text file (for example json). I can use head order for the reading of the first lines. For example: head -n 100 file.json get me 100 first lines back. What is Linux order, which I can use to read some general lines somewhere in file? For example from the line 500 to the line 700.
You can use sed: sed -n 500,700p file.json
read specific lines from the file [duplicate]
1,554,498,125,000
I found bash ignores binary zero on input when reading using the read buildin command. Is there a way around that? The task is reading from a pipe that delivers binary data chunks of 12 bytes at a time, i.e. 2 ints of 16 bit and 2 ints of 32 bit. Data rate is low, performance no issue. Since bash variables are C-style...
bash variables can't store NUL bytes (only zsh does, though see also ksh93's printf %B and typeset -b using base64 encoding). Its read builtin will also skip NUL bytes in input. However, here, you could use: LC_ALL=C IFS= read -rd '' -n1 c That is read up to one byte off a NUL-delimited record. So if $c is empty, th...
How to read binary data including zero bytes using BASH builtin read?
1,554,498,125,000
I want to read from stdin until a string delimiter MARKER=$'\0'"BRISH_MARKER" is encountered. I tried: ❯ unset br ; print -rn -- hi${MARKER}world | { IFS= read -d "$MARKER" -r br ; cat -v } ; echo ; typeset -p br Which gives: BRISH_MARKERworld typeset br=hi So read is only using the first character of the given ...
Yes read -d works only with single-character delimiters (in bash and ksh93, it only works with single-byte delimiters). Reading up to a delimiter also means that you need to read one byte at a time (especially with non-seekable inputs such as pipes) to make sure you don't read past the delimiter, which makes it ineffi...
zsh: Read from stdin until a string delimiter
1,554,498,125,000
So I have an auto clicker script that is this simple command: Tribute xdotool click --delay 5 --repeat 900000 1 I have to switch to the terminal and Ctrl-C interrupt the script to stop it. Then just run it again to restart. So I started to use the read command to check for key input to avoid this switching back and ...
By typing xinput --list, you get a list of all the input devices in your system. You can also programmatically get the state of each key using xinput --query-state DEVICE_ID. 1 class : KeyClass key[0]=up key[1]=up key[2]=up ... First, you will need to figure out the keycode you want to use. You can do thi...
How to make an auto clicker with global start and stop key
1,554,498,125,000
My bash script needs to read the variables from a text file that contains hundreds of variables, most of which conform to standard bash variable syntax (e.g., VAR1=VALUE1). However, a few lines in this file can be problematic, and I hope to find a simple solution to reading them into bash. Here's what the file looks ...
While you can transform this file to be a shell snippet, it's tricky. You need to make sure that all shell special characters are properly quoted. The easiest way to do that is to put single quotes around the value and replace single quotes inside the value by '\''. You can then put the result into a temporary file an...
Read non-bash variables from a file into bash script
1,554,498,125,000
I am trying to redirect the output of a python script as an input into an interactive shell script. test.py print('Hello') print('world') Say test.py is as above prints "Hello world" which is feed to two variables using Here string redirection as below Interactive script : read a b <<< `python3 test.py` This is not...
read a b reads two words from one line (words delimited by $IFS characters and word and line delimiters escaped with \). Your python script outputs 2 lines. Older versions of bash had a bug in that cmd <<< $var or cmd <<< $(cmd2) was applying word splitting to the expansion of $var and $(cmd2) and joining the resultin...
backtick or Here string or read is not working as expected in RHEL 8
1,554,498,125,000
I'm using read to read a path from a user like so: read -p "Input the file name: " FilePath The user now enters this string: \Supernova\projects\ui\nebula What can I do to replace \ with /. The result I want is: /Supernova/projects/ui/nebula By the way, the command: echo $FilePath outputs the result: Supernovap...
The problem is that read treats backslash in its input as an escape operator (to escape the separators when using read word1 word2 and the newline to allow line continuation). To do what you want, you need to add the -r switch to read which tells it not to do that backslash processing, and you also need to set $IFS to...
Read a variable with "read" and preserve backslashes entered by the user
1,554,498,125,000
#!/bin/bash echo 123456789 > out.txt exec 3<> out.txt read -n 4 <&3 echo -n 5 >&3 exec 3>&- Was asked the content of out.txt at the end of script, in an interview written exam. I did run the script afterwords and it gave me 123456789. Yet I have no idea what is going on in the script, especially the parts with the e...
echo 123456789 > out.txt writes the string 123456789 in out.txt file. The exec 3<>out.txt construct opens the file out.txt for reading < and writing > and attaches it to file descriptor #3. read -n 4 <&3 reads 4 characters. echo -n 5 >&3 writes 5 (replacing 5 by 5). exec 3>&- closes file descriptor #3. Resulting in ca...
What is this script doing?
1,554,498,125,000
I have a string -w o rd. I need to split it to w o r d or to an array for 'w' 'o' 'r' 'd' it doesn't really matter. I have tried the following IFS='\0- ' read -a string <<< "-w o rd" echo ${string[*]} rd isn't getting split. How can I make it get split
You can't use IFS in bash to split on nothing (it has to be on a character). There's no characters between r and d in rd. No space and no character isn't the same as the null character. If you want each character as a separate element in the array, one way I can think of is to read each character individually and app...
How can I split a string to letters with IFS and read at no space/null, space and at a character -?
1,554,498,125,000
I have this script: #!/bin/bash function main { while read -r file; do do_something "$file" done <<< $(find . -type f 2>/dev/null) } function do_something{ echo file:$@ } On linux, it works fine, but on Mac (Bash version 5.2), it treats all files found as one item, and pass the whole string without line-br...
In older versions of bash, in <<< $param$((arith))$(cmdsubst) where <<< is the here-string operator copied from zsh, such unquoted expansions were subject to $IFS-splitting and the resulting words joined back with space and the result stored in the temporary file which makes up the target of the redirection. That was ...
"read -r" builtin in bash script acts differently on Mac
1,554,498,125,000
I have problem with a simple read. I read a list of items xml items and then I work with them. In some point I need to ask if Im sure and accept this response in a variable. My problem is that if I ask into the "while read linea" the "read -p ..." is ignored and I can't answer the question. xml2 < list | egrep "item...
use this one instead : read -p "Are you sure: " sure </dev/tty Quotes should be ascii 0x22, not UNICODE U-201c “ and U-201d ”.
Read line is ignored
1,554,498,125,000
I have two files: In one I have a list of strings, which need to removed if the corresponding line in the other file contains a string "NOPE". If it contains "YES" it stays there. Note that removing one line might destroy the order. The format is like this: 1.txt: Jimmy John Johnson 2.txt: YES NOPE YES Correct Outpu...
You could so something like paste 2.txt 1.txt | awk '$1 == "YES" {print $2}' (for single-word strings) or awk 'NR==FNR && $0=="YES" {i[FNR]; next} FNR in i' 2.txt 1.txt
How to sort out the wrong entries in the most simple way depending on the corresponding line in the other file?
1,554,498,125,000
Suppose we have the following program, which calls read() twice: #include <stdio.h> #include <unistd.h> #define SIZE 0x100 int main(void) { char buffer1[SIZE]; char buffer2[SIZE]; printf("Enter first input: \n"); fflush(stdout); read(STDIN_FILENO, buffer1, SIZE); printf("Enter second input:...
This is likely not to provide an acceptable solution to you, but considering that: the source code cannot be changed the shell can not change where the open file descriptors of a running program point to, nor make a running program stop reading from a file descriptor Some alternatives you are left with (short o...
Providing input for multiple read(stdin) calls via bash input redirection
1,554,498,125,000
Say we have file like so: foo1 bar foo2 foo2 bar bar bar foo3 I want it reduced to: foo1 bar foo2 bar foo3 basically removing duplicates only if they are adjacent...I started writing a bash function but realized I have no idea how to do this: remove_duplicate_adjacent_lines(){ prev=''; while read line; do ...
This is exactly what the uniq utility is for: $ uniq <File foo1 bar foo2 bar foo3 A good example might be bash history: history | uniq The above won't work because of line numbers, but this will: cat ~/.bash_history | uniq will remove repeated adjacent commands From man uniq: Filter adjacent matching lines from IN...
Remove duplicate adjacent lines from file
1,554,498,125,000
bash builtin command read is said to accept input from stdin, but why does the following not read in anything? $ printf "%s" "a b" | read line $ printf "%s" "$line" $ Thanks.
The problem is not with read itself, but with the pipe. In bash, that causes the second command (read, in this case) to run in a subshell. So it will actually read into a line variable, only that variable exists in a subshell and will vanish as soon as the pipeline completes. (Note that other shells behave differently...
How can I make `read` read from stdin? [duplicate]
1,554,498,125,000
I'm trying to read from two fifos (read from one, if there's no content read from the other, and if there's no content in neither of both try it again later), but it keeps blocking the process (even with the timeout option). I've followed some other questions that reads from files (How to read from two input files usi...
I've seen the conversation between @etosan and @ilkkachu and I've tested your proposal of using exec fd<>fifo and it works now. I'm not sure if that involves some kind of problem (as @etosan have said) but at least it works now. exec 3<>"$socket_fifo" # to not block the read while true; do while IFS= r...
Reading from two fifos in Bash
1,554,498,125,000
I'm trying to figure out how I can reliably loop a read on a pt master I have. I open the ptmx, grant and unlock it as per usual: * ptmx stuff */ /* get the master (ptmx) */ int32_t masterfd = open("/dev/ptmx", O_RDWR | O_NOCTTY); if(masterfd < 0){ perror("open"); exit(EXIT_FAILURE); }; /* grant access to the...
It's very simple: you should open and keep open a handle to the slave side of the pty in the program handling the master side. After you got the name with ptsname(3), open(2) it. I noticed a thread making a call to this: ioctl(3, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, {B38400 opost isig icano...
read(2) blocking behaviour changes when pts is closed resulting in read() returning error: -1 (EIO)
1,554,498,125,000
The Wikipedia LTO article says that every LTO drive can read out the memory chip of a tape via 13.56 MHz NFC. I expect here to find serial numbers, tape properties and usage data. How can I read this data with free and open-source software on a Linux system?
Method.1 LTO DRIVE LTO drive has a RFID reader inside to read data from the chip. The client can access this via SCSI command. Specifically, READ ATTRIBUTE command (Operation Code: 8C). READ ATTRIBUTE command shall be invoked along with Attribute Identifier that specifies the data field to be transferred. For example,...
Read the chip data from LTO tapes
1,554,498,125,000
If I do this: echo <(cat) I get: /dev/fd/63 so say at the command line I have: myapp -f <(cat) when I run it I get this error: You need to pass a file after the -f flag. The resolved file path was: '/dev/fd/63'. This path did not appear to exist on the filesystem. How can I determine if the result of the proces...
To determine, in Bash, whether a string value is a path on your current system, use [[ -e "$path" ]]. This checks whether the path exists, and doesn't make any assumptions about the type of file it points to.
How to determine if result of process substitution is a file path
1,554,498,125,000
I wrote this testing code, and find that this program can always read the file successfully even after I canceled the read permission when running getchar(). #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdint.h> #include <sys/types.h> int main(){ int f = open("a.txt",O_RDONLY); uint8...
Yes, permissions are only checked at open time and recorded. So you can't write to a file descriptor that you opened for read-only access regardless of if you are potentially able to write to the file. The kernel consults in-memory inodes rather than the ones stored in the filesystem. They differ in the reference coun...
Does Linux kernel check file permissions on inode or open file description?
1,554,498,125,000
I am trying to set a while read loop line to read an input text file line by line and pass two strings as variables on each line in the text file. while IFS= read -r line do # Read and pass two path strings as variables. read path1 path2 echo "$path1" echo "$path2" done < "$1" It seems to process...
The second read inside the body of the loop is incorrect here. It actually goes one line ahead than your first read call as part of the while loop. So for your requirement just read those variables as part of the first read while read -r path1 path2; do echo "$path1" echo "$path2" done < "$1" As you see here,...
Problem using read command within while read loop
1,554,498,125,000
I'm trying to write a simple script that read from standard input, using ; character as delimiter to terminate the input line and that allows user to edit line. Here is my test script: #!/bin/bash while true; do read -e -d ";" -t 180 -p "><> " srcCommand if [ $? != 0 ]; then echo "end;" echo "" ex...
I'd use zsh where the line editor has many more capabilities and is a lot more customizable: #! /bin/zsh - insert-and-accept() { zle self-insert # RBUFFER= # to discard everything on the right zle accept-line } zle -N insert-and-accept bindkey ";" insert-and-accept bindkey "^M" self-insert vared -p "><> " -c src...
How can I print out the delimiter character and allow user to edit line while reading standard input?
1,554,498,125,000
I have bash script that have input commands. echo "Enter the id: " read id I'd like to know if there's a way I can limit the character can I input in the for id. I mean example he can only enter 5 characters for id. is that possible? Thank you.
So with bash there are (at least) two options. The first is read -n 5. This may sound like it meets your needs. From the man page -n nchars read returns after reading nchars characters rather than waiting for a complete line of input, but honor a delim- iter if fewer than nchars characters ...
Max character length for Read command (input)
1,554,498,125,000
I use bash printf function to print ASCII codes of characters in an input file, but for some reason printf outputs ascii code 0 for LF characters, instead of 10. Any ideas why? while IFS= read -r -n1 c do ch=$(LC_CTYPE=C printf "%d\n" "'$c") # convert to integer echo "ch=$ch" done < input_file_name To be honest, I am...
first your printf function works perfectly $ export c=" " $ LC_CTYPE=C printf "%d\n" "'$c" 32 But running the script line with -vx on shows that the data getting to this line is wrong ( I won't paste this output ) So I figure it is the read that is wrong. The default EOL delimiter for read is newline, so I tried alt...
bash read of a newline, printf reports character 0
1,554,498,125,000
I'm trying to read user input char by char, silently, as follows: while [ 1 ]; do read -s -N 1 ... done While this loop works perfectly using VNC (xterm), it works only partially using putty (xterm) or a Linux terminal, and most of other text terminals. The problem is encountered when I become "wild" with the ke...
read -s disables the terminal echo only for the duration of that read command. So if you type something in between two read commands, the terminal driver will echo it back. You should disable echo and then call read in your loop without -s: if [ -t 0 ]; then saved=$(stty -g) stty -echo fi while read -rN1; do ......
Reading char-by-char silently does not work
1,554,498,125,000
An application is loaded by mounting its content from a distant machine to a local dir. On some machines there is slow performance and I'd like to check the read speed of the files in the mounted dir. hdparm -Tt /dev/<dev_name> works for drives and it is exactly what I require from the output but I cannot seem to run...
bonnie++ is a commonly suggested tool for checking disk performance in a directory: bonnie++ -d $DIREC For quick order of magnitude answers I might be inclined to use pv (pipe view) cat file | pv > disk
Read speed from a mounted directory
1,461,439,018,000
In a bash script I'm reading some user input with read. Now I want to provide the possibility to auto-complete the input by hitting the Tab key. Easy example: Let's say, the user shall type in a name from a limited domain. In the script I have an array containing all valid names, those should be included in the auto-c...
Use rlwrap, a readline wrapper. From man rlwrap rlwrap runs the specified command, intercepting user input in order to provide readline's line editing, persistent history and completion. and from the Debian rlwrap package description: This package provides a small utility that uses the GNU readline library to allow...
Bash script - auto complete for user input based on array data
1,461,439,018,000
I have an album of 11 .flac audio files. (edit: since this issue has been resolved, it's now clear that the precise names and content of the files are irrelevant, so I've renamed them): > find . -name "*.flac" ./two.flac ./ten.flac ./nine.flac ./eight.flac ./seven.flac ./three.flac ./four.flac ./five.flac ./one.flac ....
Unless you have a directory tree of files (not mentioned, and not shown in your example dataset), you can use a simple loop to process the files for f in *.flac do w="${f%.flac}.wav" ffmpeg -i "$f" -sample_fmt s16 -ar 44100 "$w" done If you really do have a hierarchy of files you can incorporate this into a f...
Bash variable truncated when passed into ffmpeg
1,461,439,018,000
I have this very simple script: #!/bin/bash read local _test echo "_test: $_test" This is the output. $ ./jltest.sh sdfsdfs _test: I want the variable _test to be local only. Is this possible?
The local builtin only works inside a function. Any variable you set in your script will already be "local" to the script though unless you explicitly export it. So if you remove that it will work as expected: #!/bin/bash read _test echo "_test: $_test" Or you could make it a function: my_read () { local _test ...
How to read keyboard input and assign it to a local variable?
1,461,439,018,000
I have this line of code that reads a text file line by line. The text file is sometimes generated by a Windows user, sometimes by a Unix user. Therefore, sometimes I see \r\n at the end of the line and sometimes I see only \n. I want my script to be able to deal with both scenarios and reach each line separately rega...
If you have some files that are DOS text file and some that are Unix text files, you script could pass all data through dos2unix: dos2unix <filename | while IFS= read stuff; do # do things with "$stuff" done Unix text files would be unmodified by this. To additionally cope with Mac line breaks, I believe you shou...
Treat "\r" as nothing in "while read -r"
1,461,439,018,000
I'm trying to pipe a string with special characters (e.g. HG@eg3,l'{TT\"C! to another command (termux-clipboard-set) with the read program. It seems that read was designed to create a temporary variable (e.g. read temp) that should be then passed to another command (e.g. termux-clipboard-set $temp). I'm wondering if t...
For bash, read is not a program. read is a builtin. Simplified, read reads stdin and assigns that input to a variable. The read builtin does not produce any output on stdout, so trying to pipe stdout to something does not produce anything. The question is why. According to the man page, Usage termux-clipboard-set [t...
pipe the read command?
1,461,439,018,000
I have a DE_CopyOldToNew.txt file with a whole bunch of copy commands for copying old file names to new file names. The file contains rows like : cp /migrationfiles/Company\ Name\ GmbH/2014.138_Old\ File\ Name.pdf /appl/data/docs/202403/DE_2014.138_NewFile_1.pdf cp /migrationfiles/Company\ Name\ GmbH/2014.139_Old\ Fil...
You say, I have a DE_CopyOldToNew.txt file with a whole bunch of copy commands for copying old file names to new file names. ... and you say you want to execute these cp commands. You are in luck because you have a shell script, i.e., a file containing a set of commands to be executed in order by a shell. All you n...
Execute copy commands from file
1,461,439,018,000
Problem 1: I want to get the array items as user inputs at runtime; print the items and print the array length. This is what I have: read -a myarray echo "array items" ${myarray[@]} echo "array length" ${#myarray[@]} At runtime, I gave the following as input, $ ("apple fruit" "orange" "grapes") The output was, array...
Problem 1: In your example, read does not get its input from a command line argument, but from stdin. As such, the input it receives does not go through bash's string parser. Instead, it is treated as a literal string, delimited by spaces. So with your input, your array values become: [0]->("apple [1]->fruit" [2]-...
Reading array values as user input gives wrong array length and only -a or -p works in read
1,461,439,018,000
I need to write a script that will add a line to a text file if Enter is pressed. But, if Ctrl+D is pressed, I need to exit that loop in the bash. touch texttest.txt LINE="0" while true; do read LINE; if [ "$LINE" == "^D" ]; then break else echo "$LINE" >> texttest.txt fi done ...
You're overthinking it. All you need is this: cat > texttest.txt Cat will read from STDIN if you've not told it different. Since it's reading from STDIN, it will react to the control character Ctrl+D without your having to specify it. And since Ctrl+D is the only thing that will finish the cat subprocess, you don't...
Bash Script using read needs to stop executing on Ctrl+D
1,461,439,018,000
Hello I have 2 files with the first file containing a few values for example powershell vectormaps JuniperSA and the second file containing values and and ID appid uid SplunkforSnort 340 powershell 610 vectormaps 729 JuniperSA 826 postfix 933 SplunkforJuniperSRX 929 TA-barracuda_webfilter 952 TA-dragon-ips 954 dhcpd ...
Using awk $ awk 'FNR==NR {a[$1]=$2; next} {$(NF+1)=a[$1]}1' file2 file1 powershell 610 vectormaps 729 JuniperSA 826
Trying to find complete string values from one file based on another file using AWK
1,461,439,018,000
I am trying to use read, to read from a file descriptor, like so: read -u fd as in in this link. Here is the code I am using in a bash script: MESSAGE=$(read -u $NODE_CHANNEL_FD) echo " parent message => $MESSAGE" >&2 The exact error message: read: Illegal option -u Anyone know what this could possibly be about?
The error message suggests that you are in fact not executing the script using bash. Either make the script executable and add a proper #!-line on the first line of the script, e.g. #!/bin/bash Or, execute the script with bash explicitly: $ bash script.sh You should treat sh and bash as implementing separate languag...
read: illegal option -u
1,461,439,018,000
How can I take input from read, split the words up by spaces, and then put those words into an array? What I want is: $ read sentence this is a sentence $ echo $sentence[1] this $ echo $sentence[2] is (and so on...) I'm using this to process English sentences for a text adventure.
If you are using bash, its read command has a -a option for that. From help read Options: -a array assign the words read to sequential indices of the array variable ARRAY, starting at zero So $ read -a s This is a sentence. Note that the resulting array is zero indexed, so $ echo "${s[0]}" This $ echo "$...
Split words from `read` and store to array?
1,461,439,018,000
Why does this show blank lines instead of folders found by find? ssh -o stricthostkeychecking=no -o userknownhostsfile=/dev/null \ -o batchmode=yes -o passwordauthentication=no [email protected] \ "sudo find /folder/CFGKCP/KCS\ Pro/Job\ Setup -name JOBCFG.info \ | while read linea; do echo $linea; done";
As Romeo pointed out, you're using double quotes around your command. That means your variables are being expanded before doing the ssh command. So the body of the while loop is echo $linea and before the ssh linea probably doesn't exist so the command that is passed will become just echo with linea being replaced ...
Why does read with pipeline fail in an ssh session?
1,461,439,018,000
My goal is to initialize multiple bash variables from the output of one single command. Specifically, line i should be the value of variable i. Example: My command is a Python program with the name init.py: if __name__ == '__main__': print("Value of A") print("Value of B") print() print("Value of D") Desired ...
If you have an empty line, using IFS won't work, because multiple \n are squeezed. However, you can use readarray: readarray -t arr < <(python init.py) echo "A='${arr[0]}', B='${arr[1]}', C='${arr[2]}', D='${arr[3]}'" Add -d '' to delimit by \0: readarray -d '' -t arr < <(python init.py) From man bash: -d The ...
Initialize several bash variables with the output of a single command
1,461,439,018,000
According to this manual -r for read: Do not allow backslashes to escape any characters I understand that generally, the read shell builtin gets input and creates a variable which holds that input as a string in which backslashes would be just literal components and wouldn't escape anything anyway. Is read -r only u...
I understand that generally, the read shell builtin gets input and creates a variable which holds that input as a string in which backslashes would be just literal components and wouldn't escape anything anyway. Plain read var, without -r, when given the input foo\bar, would store in var the string foobar. It treats...
Is read -r only used in rare exceptional usecases of read?
1,461,439,018,000
I found this to get user input from the command line. But it is failing into recognizing the new line characters I put into the input. Doing: #!/bin/bash read -e -p "Multiline input=" variable; printf "'variable=%s'" "${variable}"; Typing 'multi\nline' on Multiline input= makes printf output 'variable=multinline' Ty...
If typing in \n (as in the two characters \ and n) is acceptable, then you can use printf to interpret it: #!/bin/bash IFS= read -rep "Multiline input=" variable; printf -v variable "%b" "$variable" printf "'variable=%s'\n" "${variable}"; For example: ~ ./foo.sh Multiline input=foo\nbar 'variable=foo bar' From the b...
How to read input lines with newline characters from command line?
1,461,439,018,000
When I run: du -sh ./*/ I get the following error: sort: read failed: ./folder/: Is a directory How do I fix this? Is there something wrong with sort on my system. I am running x86_64 Linux 4.16.8-1-ARCH.
The du utility will never produce that error message. The message comes from sort. The sort utility produces that message when given a command line argument that is a folder when it expects a file. Therefore, it is reasonable to assume that du is in fact a shell function or an alias that calls sort in such a way tha...
sort: read failed: ./folder/: Is a directory [closed]
1,461,439,018,000
Here is a test question that I am stuck with: Which output will the following command sequence produce? echo '1 2 3 4 5 6' | while read a b c; do echo result: $c $b $a; done And the correct answer is: 3 4 5 6 2 1 I have no clue why. Can someone please explain it to me? (At first I thought the answer was 3 2 1.)
From the read manpage: Reads a single line from the standard input, or from file descriptor FD if the -u option is supplied. The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on, with any leftover words...
sequence command and test question
1,461,439,018,000
In bash, is there any way to read in user input but still allow bash variable expansion? I am trying to request the user enter a path in the middle of a program but since ~ and other variables are not expanded as a part of the read builtin, users have to enter in an absolute path. Example: When a user enters a path in...
A naive way would be: eval "dirin=$dirin" What that does is evaluate the expansion of dirin=$dirin as shell code. With dirin containing ~/foo, it's actually evaluating: dirin=~/foo It's easy to see the limitations. With a dirin containing foo bar, that becomes: dirin=foo bar So it's running bar with dirin=foo in it...
Can Bash Variable Expansion be performed directly on user input?
1,461,439,018,000
script #!/bin/bash -- # record from microphone rec --channels 1 /tmp/rec.sox trim 0.9 band 4k noiseprof /tmp/noiseprof && # convert to mp3 sox /tmp/rec.sox --compression 0.01 /tmp/rec.mp3 trim 0 -0.1 && # play recording to test for noise play /tmp/rec.mp3 && printf "\nRemove noise? " read reply # If there's n...
What happens is that one of your SoX programs (sox, play, rec) has changed how stdin is behaving, making it non-blocking. Typically, something is calling fcntl(0, F_SETFL, O_NONBLOCK). When a call to the read() system call is made on a non-blocking file descriptor, the call does not wait: either there is already somet...
Why does `read` fail saying "read error: 0: Resource temporarily unavailable"?
1,461,439,018,000
If I run read -r -s INPUT And then interrupt it with Ctrl-C, then the terminal stays in a state where all the input characters are not shown. How can I restore the terminal after such an incident?
The command used to reset the terminal is aptly named: reset However, this would likely clear the terminal as well. You may also try stty echo which would turn on echoing of what you type, or stty sane which should get your terminal back into a sane state. If the Enter key does not seem to work, you may use Ctrl+J ...
Reset terminal after interrupting `read -r -s`
1,461,439,018,000
While reading an script, the shell will read the script from a file, or from a pipe or possibly, some other source (stdin ?). The input may not be seek able under some corner conditions (no way to rewind the file position to a previous position). It has been said that read reads stdin one byte at a time until it find...
Yes for a POSIX compliant shell. The bash developer had this to say: POSIX requires it for scripts that are read from stdin. When reading from a script given as an argument, bash reads blocks. And, indeed, the POSIX spec says this (emphasis mine): When the shell is using standard input and it invokes a command that...
Should the shell read (an script) one character at a time?
1,461,439,018,000
I'm trying to pipe a command's output to the read builtin of my shell and I get a different behaviour for zsh and bash: $ bash -c 'echo hello | read test; echo $test' $ zsh -c 'echo hello | read test; echo $test' hello Though that doesn't work in bash, the following works for both: $ bash -c 'echo hello | while re...
You are observing the results from what has not been standardized with POSIX. POSIX does not standarize how the interpreter runs a pipe. With the historic Bourne Shell, the rightmost program in a pipeline is not even a child of the main shell. The reason for doing it this way is because this implementation is slow bu...
read from stdin works differently in bash and zsh [duplicate]
1,461,439,018,000
I'd like to know how to emulate the ICANON behavior of ^D: namely, trigger an immediate, even zero-byte, read in the program on the other end of a FIFO or PTY or socket or somesuch. In particular, I have a program whose specification is that it reads a script on stdin up until it gets a zero byte read, then reads inp...
As far as I know, this behavior is unique to terminal devices, so that's what you have to use. Use a pseudo-tty whose slave side is in ICANON mode, and write Ctl-d ('\4') to the master side.
Triggering zero-byte reads on FIFO/pty
1,461,439,018,000
I am very novice with scripting and I cannot figure this out. I'm trying to know if there is something to read and if not then
With bash specifically, read -t0 will return true if there's something to read or on stdin or the end of input has been reached and false otherwise. if read -t0; then echo "there's something to be read on stdin, or end-of-file is reached" else echo "there's nothing that may be read from stdin at the moment" fi No...
How to find out if there is something to read before calling while read?
1,461,439,018,000
For example: I want user to input A=a and I have the command which I guess is totally wrong. read -p "Enter something:" frsstring=secstring echo $frsstring echo $secstring ````````````````````````````````````````````````````````````
I don't know how could it be done with one command, but you could read the entire line, and then split it in the desired variables: #!/bin/bash read -p "Enter something:" line frsstring=`echo "$line" | cut -f1 -d'='` secstring=`echo "$line" | cut -f2 -d'='` echo $frsstring echo $secstring I hope it could help
How to read two variables under one read command and echo them separately?
1,461,439,018,000
I created a persistent Debian 9 live usb. The persistence is configured with / union. An unexpected consequence, although obvious in hindsight, is the system lags on non-cached reads: holmes@bakerst:~$ # WRITE to disk holmes@bakerst:~$ dd if=/dev/zero of=tempfile bs=1M count=1024; sync 1024+0 records in 1024+0 recor...
Get a faster USB 3 pendrive, or maybe even a USB SSD :-) You can easily improve reading from the image of the iso file (after a slow start), put all the content of the squash file system into RAM with the boot option toram, but I don't think it is easy or meaningful to do that with the content of the file/partition f...
Speed up persistent live usb disk operations
1,461,439,018,000
I am using GNU bash - version 4.2.10(1). I want to read multiple variables using single read command in shell script. So i tried as below: echo " Enter P N R : " read P N R but it's not working. It just ask for single value of P variable and returns prompt. I googled it but don't found any solution.
read, without -r expects words on input to be delimited by the characters of the $IFS special parameter (by default SPC, TAB and NL, though as read reads only one line unless it ends in backslash, NL can't count) where backslash can be used to escape the separator or allow a line to be continued on the next physical l...
How to use multiple variable for input with read command?
1,461,439,018,000
I opened two terminals (/dev/pts/1 and /dev/pts/2) and started my application from /dev/pts/1. I want to read in real time from /dev/pts/2 but my code doesn't work: actually some of the symbols are shown on the /dev/pts/1 and some of them are shown on the /dev/pts/2 FILE *f = fopen("dev/pts/2", "r"); while(1) { ch...
You have two processes reading from /dev/pts/2. One is the shell (or some application) running there, the other is your application on pts/1. It's random which one is faster reading the available bytes.
How to read from another terminal?
1,461,439,018,000
I use sed with <<< and read to assign all words in a string to variables. What I do is: read -a A0 <<< $(sed '2q;d' /proc/stat) Hence, sed reads the second line of the file file and immediately quits. The line sed has read in is fed to <<< which does expands the input it receives from sed and read -a assign the resul...
You can use array assignment directly: A0=($(sed '2q;d' /proc/stat)) Beware that this performs globbing: if the output of the command contains shell wildcards, then the words containing wildcards are replaced by the list of matching files if there are any. If the output of the command might contain one of the charact...
Using sed with herestring (<<<) and read -a
1,461,439,018,000
I have a list of filenames in a file and want to do let the user decide what to do with each. In bash, iterating over filenames is not trivial in itself, so I followed this answer: #!/bin/bash while IFS= read -r THELINE; do read -n 1 -p "Print line? [y/n] " answer; if [ ${answer} = "y" ]; then echo "${THEL...
First, the error from [ is because answer is empty, so [ sees three arguments: =, y and ]. Always put double quotes around variable substitutions: if [ "$answer" = "y" ]. The reason $answer is empty fd 0 is busy with the file input due to the redirection <tester over the while loop. while IFS= read -r line <&3 do ...
Nested read fails
1,461,439,018,000
I have this script: #!/usr/bin/env bash main() { while true; do read -r -ep "> " input history -s "$input" echo "$input" done } main which works well for single line strings. Now I'm looking to allow the user to enter multiline strings, e.g. something like the following: > foo \ > bar foobar how do ...
You explicitly disable the special handling of backslash with -r. If you remove -r from your read invocation, you will be able to read your input with the escaped newline: $ read input hello \ > world $ echo "$input" hello world Compare that with what happens if you use -r (which is usually what you want to do): $ re...
How to read multiline input in bash
1,461,439,018,000
on a POSIX shell, no Python and no awk available (so don't bother telling me I should use a "real" programming language) I have to loop through a csv file. https://datacadamia.com/lang/bash/read My initial guess was : while IFS=";" read -r rec_name rec_version rec_license rec_origin rec_modification rec_newlicense do ...
Only <() is non-POSIX in your first try, so just use normal pipes instead: tail -n +2 "${output_file%%.*}.csv" | while IFS=";" read -r rec_name rec_version rec_license rec_origin rec_modification rec_newlicense do if [ "$name" = "$rec_name" ]; then if [ "$license" = "$rec_license" ]; then ...
posix bash, how to read a csv file and ignore some columns?
1,461,439,018,000
In this GitHub repository I have a directory named nwsm. This directory contains the file nwsm.sh that contains a master script (a script that runs other scripts). The directory also contains a few other files which contain sub-scripts that the master script executes, each one at a time. In nwsm.sh I declare a few var...
If you mean you just want to have the variables visible when the main script runs the other scripts, then you just export them: $ cat main.sh #!/bin/sh read foo export foo ./foo.sh $ cat foo.sh #!/bin/sh echo "foo is $foo" $ ./main.sh blah foo is blah $ The other scripts run as subprocesses of the main script, ...
Using variable values defined in one file, in files in the same directory
1,461,439,018,000
Pressing Enter still does its delimiter job but the read command just ends quietly, abstaining from messing with the console scrolling. Basically a read -s that affects only the endline.
You could invoke zsh's line editor (which is fully configurable and generally a lot more advanced than readline (which bash can invoke with read -e)) like: var=$( saved_tty=$(stty -g) var=default-value zsh -c ' zle-line-finish() { # hook run upon leaving the line editor (zle) CURSOR=$#BUFFER # move the c...
How do I get `read` to echo all input except for the endline at the end of the typing?
1,461,439,018,000
I'm trying to write a simple shell script for launching commands with urxvt. The idea is this (not the complete script, just the idea): PRMPT="read -r CMD" urxvt -g 55x6-20+20 -e $PRMPT CMD There are two problems with this script. The first one is that read is not fit for this kind of task, as it would ignore options...
what is your goal? echo is executable (/bin/echo), read is builtin. -e means execute an executable. If you wanna use a builtin function of your shell (bash?) use urxvt -e /bin/bash -c read -r CMD
Understanding read built-in
1,461,439,018,000
I'm trying to capture a key press in a shell script (e.g. using read) and not to echo it. The three methods I found were stty -echo, the -s switch and stream redirection. However, on macOS, which seems to use a FreeBSD implementation, none of these work consistently. The following script shows the issue: while true; d...
In your loop, there is a short window of time between the "stty echo" at the end of the loop and the "stty -echo" at the next iteration. Keyboard input received during this window will be echoed, even though no read command is waiting for it. If you don't want echoes, don't call "stty echo" 😉
How to suppress echo of buggy read function
1,461,439,018,000
I have this working: % cat read.sh !/bin/sh file=list.txt while read line do echo "$line" cut -d' ' -f27 | sed -n '$p' > file2 done < "$file" % cat list.txt sftp> #!/bin/sh sftp> sftp> cd u/aaa sftp> ls -lrt x_*.csv -rwxr-xr-x 0 1001 1001 12274972 May 13 21:07 x_20150501.csv -rw-r--r-- 0 1001 ...
You can combine all the actions in one command: sftp user@host:/path/to/file/$(tail -1 file1.txt |tr -s ' ' |cut -d ' ' -f 9) This will fetch the file into the current working directory. If you need to fetch the file into another directory specify the destination directory as a next argument to the sftp command.
Shell read script for sftp
1,461,439,018,000
I am trying to make a clip out of video file by playing it only for certain interval. make_mclip.sh #!/bin/bash mediafile=$@ mediafile_fullpath=$PWD/./$mediafile tmpedlfile=$(mktemp) mplayer -edlout $tmpedlfile "$mediafile" &> /dev/null cat $tmpedlfile | while read f do startpos=$(echo $f | awk '{print $1}') ...
mplayer is "consuming" tmpedlfile remaining content. You need to add an option for it not to ignore its stdin: mplayer -noconsolecontrols -ss $startpos -endpos $length "$mediafile" &> /dev/null
while loop is running only once?
1,461,439,018,000
Before continuing, please bear in mind that I am aware that I could configure keyboard shortcuts through the settings menu, but that would not be of use for my end goal. I'm trying to create a simple script to take a single keypress as the input, then perform an action. Ideally, I would like to execute a command when ...
Try this: #! /usr/bin/env bash read -p "press key " -sn 1 key #you can use -p "Message" instead of using echo "Message" before. if [ "$key" == $'\x1b' ]; then read -sn2 chars if [[ $chars = '[A' ]];then echo You pressed 'Up' key fi else echo Pressed another key fi When you type keys like Up...
Specify a Keypress as a variable for "if" command
1,590,801,567,000
How to parse line by line from dmesg command?, i try using a while and read: while read -r L; do echo "line: ${L}"; done < <(dmesg -c --level=err) But can not echo the lines. I try using: LINES=$(dmesg -c --level=err); while read -r L; do echo "line: ${L}"; done <<< "$LINES" But echo only a one line without ...
I guess that you forget that -c switch is to delete the dmesg content after the first invocation. It's the simple reason why you don't have line echo-ed. The first snippet is valid bash code. Ensure your default shell is bash ! [[ $SHELL == *bash ]] && echo 'bash is the default shell' || echo >&2 "WTF"
How to parse line by line from dmesg in bash?
1,590,801,567,000
I have a text.txt file like this line1 line2 line3 I want to write a script that loops over each line and echo out modified line1 modified line2 modified line3 This is the script which is a very common solution: while IFS= read -r line; do echo modified $line done <<< $(cat ~/text.txt) But the output I got was: m...
The issue is in the last line, you don't need the variable (command substitution) or cat, since read already can read the file. If you instead do this: while IFS= read -r line; do echo modified $line done < ~/text.txt It works. Additionally, your command would work if you quoted the variable like: "$(cat ~/text.txt...
Using read command to read file by line in Bash doesn't work
1,590,801,567,000
The problem is to read variables with read command dynamically from a read command in bash without knowing how many they are in advance and store them into an array . I tested with : read -p "array : " array[{0..#}] as read -p "array : " array[{0..3}] works But with no success .
From the read usage output you can actually use the -a flag. read -p "array: " -a array
How to read variables from stdin dynamically and store them into an array
1,590,801,567,000
Using read and by typing `word followed by the left arrow ←, one get $ read word^[[D The same goes for the Home and End keys that lead to ^[[H and ^[[F respectively. How can I handle those characters, so that I go backward with the left arrow ←`, at the beginning and end of what has been written with Home and End r...
readline library usually handles this, and inputrc tells you which codes are emitted. Forcing the shell into interactive mode should enable these features. curses is a library that does the full support for moving the cursor around (if you want a text editor or something). But ultimately, you have to remember, that th...
How to handle back arrows, End and Home keys in a read prompt
1,590,801,567,000
Given such situation: echo "Please enter your name" read name # user enters: john smith echo $name # prints: john What could cause read to read only the first word of the input? Is there a shell variable that controls this? I came across this in a question on Ask Ubuntu and I'm wondering how to reproduce this be...
to accept whatever the user enters, use this form IFS= read -r name That will accept leading/trailing/inner spaces as well as literal backslashes.
Input separator of the `read` builtin in Bash
1,590,801,567,000
FYI I am running busybox. I am able to send data to my ttyS1 using the following command: stty -F /dev/ttyS1 speed 115200 cs8 -cstopb -parenb -echo echo -en 'data here' > /dev/ttyS1 But when I try to read, I do this: stty -F /dev/ttyS1 speed 115200 cs8 -cstopb -parenb -echo cat /dev/ttyS1 But program ends without a...
So found answer in another forum. I will put it here, basically just add timeout timing and a while loop to constantly read the port. stty -F /dev/ttyS1 speed 115200 cs8 -cstopb -parenb -echo time 3 min 0 while [ true ]; do cat /dev/ttyS1 done That's all.
Reading data from serial port
1,590,801,567,000
I have tried to hook system calls using linux kernel module. However, when I open a pdf file using Evince, I find no open,read and write is used on this specific file, only lstat is used. Here is the strace log of strace evince folder1/test.pdf So I wonder what system call does evince use to open andread from file?
As pointed out by @ThomasDickey, you need to pass strace the -f option, in order to include the trace of all the threads. (The clone() syscalls are creating new threads, not processes, but you still need -f to have strace follow threads.) Once you're following all threads, the open becomes aparent, opening the file i...
What system call does Evince use to open pdf?
1,590,801,567,000
I have a text file which is usually filled with multiple lines which I want to "print" with a while loop. The text inside this file contains variables - my problem is, that these variables are not interpreted unlike a similar test-string containing variables stored inside the script. Is it possible to also interpret ...
It would probably make more sense to write it as: BLUE=$'\033[1;34m' NC=$'\033[0m' # No Color eval "cat << EOF $(<text_file) EOF " than using a while read loop (that's not the right syntax for reading lines btw). Of course that means that code in there would be interpreted. A $(reboot) in there for instance would ca...
Interpret variables from read in string with shell script [duplicate]
1,590,801,567,000
Is there a way to validate or confirm that the user wrote what it meant to write in read? For example, the user meant to write "Hello world!" but mistakenly wrote "Hello world@". This is very similar to contact-form validation of an email / phone field. Is there a way to prompt the user with something like "Please r...
With the bash shell, you can always do FOO=a BAR=b prompt="Please enter value twice for validation" while [[ "$FOO" != "$BAR" ]]; do echo -e $prompt read -s -p "Enter value: " FOO read -s -p "Retype to validate: " BAR prompt="\nUups, please try again" done unset -v BAR # do whatever you need to do with...
read value validation
1,590,801,567,000
I am trying to read in a file using read in bash 3.2, but read seems to be converting any instance of multiple whitespace into a single space. For example, the code below has two tabs between "hello" and "there", and three spaces between "today" and "world": while read -r LINE; do echo $LINE done <<< "hello t...
Put quotes around your variable when you print it. It's being expanded then word split so echo is getting hello and there as separate arguments. echo "$LINE" or better printf '%s\n' "$LINE" will keep your whitespace so it's not the read that's changing your whitespace, it's your not quoting the variable later
"while read -r LINE; do" is replacing multiple spaces with a single space [duplicate]
1,590,801,567,000
mapfile -t -u 7 arr < textfile gives me bash: mapfile: 7: invalid file descriptor: Bad file descriptor Other, more verbose, methods of reading files line-by-line do allow for such descriptor, e.g. read_w_while() { while IFS="" read -u 7 -r l || [[ -n "${l}" ]]; do echo "${l}" done 7< textfile The standard descripto...
mapfile -t -u 7 arr < textfile gives me. bash: mapfile: 7: invalid file descriptor: Bad file descriptor Yes, it would, if fd 7 isn't open. -u 7 only tells it to read from fd 7, it says nothing about how or where that fd should come to be. In your second snippet, there's an input redirection 7< textfile that opens a ...
How do I use a nonstandard file descriptor for reading a file into an array with mapfile?
1,590,801,567,000
When I give this command: $echo -n "Hello" Hello$ I get the above output. This means echo -n prints the string without the terminating newline. Now, I pipe the output to read, where the read command is supposed to keep reading until it encounters a newline. $echo -n "Hello" | read $ At the above command, the command p...
If you investigate the exit-status of that pipeline, you will notice that read returns 1: $ echo -n "Hello" | read $ echo $? 1 It returns 1 because it encountered an end-of-file condition and therefore failed to read more data. The input stream from echo was closed because echo had finished its task and terminated, ...
How is input terminated during piping though newline is not used?