date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,590,801,567,000
So I am often guilty of running cat on an executable file that's a binary file and my terminal usually makes some weird noises and isn't happy. Is there some accepted naming convention for giving an an extension to binary/executable encoded file? I have an executable file (the output of go build -o /tmp/api.exe . and ...
The standard naming practice for executables is to give them the name of the command they’re supposed to implement: ls, cat... There is no provision for extensions which end up ignored from the command line. To check what a file contains before feeding it to cat, run file on it: $ file /bin/ls /bin/ls: ELF 64-bit LSB ...
Standard naming practice for executables (binary file) and how to tell whether a file has has non-printable characters?
1,590,801,567,000
I use printf "input: "; read -e. I type something then I press Backspace. When reaching the last character, this deletes the input: part together with it. Backspace doesn't misbehave if I hadn't typed anything before or if I used simple read (no Readline).
A read -e calls the readline library. Which gives access to several editing tools that a plain read does not have. However, it assumes an "empty line". A workaround to this problem is to give something (like an space) to avoid the "empty line" assumption: printf 'input:'; read -e -p ' ' But since that is using the -p...
On backspace, `bash read -e` also deletes same-line printf (preexistent) text
1,590,801,567,000
The man page for grep describes the -d ACTION option as follows: If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. [...] Intuitively, I would expect this to mean that a directory bar is treated (for grepping purposes) a...
Directories do not have an intrinsic representation as text. Many Unix variants allow programs to read from a directory as if it was a regular file, but this is mostly useless since the format of the content depends on the filesystem. Some modern Unix variants, including Linux, outright blocks programs from reading a ...
Why does "grep foo bar" print "grep: bar: Is a directory" instead of printing any filenames in bar/ that match the pattern "foo"?
1,590,801,567,000
I have a here document inside a bash script. I want to read a value from it like that : su myUser<<SESSION set -x echo -n "Enter your name and press [ENTER]: " read name echo "the name is $name" SESSION But when I launch this script from another user, bash does not stop himself to wait for an input and ignore the r...
As L. Scott Johnson correctly found, the read reads from standard input. The standard input in the shell that su runs is connected to the here-document, so the read reads the literal string echo "the name is " (note that since the here-document is unquoted, the $name has already been expanded to an empty string, or t...
Bash - here doc read input value from another user
1,590,801,567,000
I'm writing a bash script where I'm reading in a variable via read this two strings: log.*.console.log log.*.log They are separated by space. How can I rewrite the strings that the output from the variable for the next program called in the script will have them in this form ? 'log.*.console.log' 'log.*.log' I was tr...
I don't think you want to give the single quotes to gtar. In a command such as somecmd 'foo bar' 'files*.log', the shell will handle the quotes, they tell it not to treat special characters specially, and pass somecmd the arguments foo bar and files*.log. Unix programs do not get the command-line as one string, but a ...
Replace single quotes for strings divided by blank space from variable
1,590,801,567,000
I am trying to automate software update with bash script. When I am passing version number e.g 7.16.3 I get following error: ") Syntax error Invalid arithmetic operator (error token is " I could not find any answer which related when passing value from read command. My code look like below: DATE=`date +'%Y%m%d'` BSI_...
-ne does a numeric comparison, while 7.16.3 is not a number. (Even if it's called a "version number".) As it happens, as far as Bash is concerned, neither would 7.16 be, since Bash only deals with integers. The error is actually clearer within Bash's [ .. ]: $ [ 7.16.3 -ne 7.16.3 ] bash: [: 7.16.3: integer expression ...
Invalid arithmetic operator (error token is " 7.16.3 when passing float from read command
1,590,801,567,000
While reading line by line, and IFS set to null, we can write: while IFS= read -r line do echo "$line" done < <(find . -name "*.txt") Is this not the same as: while read -r do echo "$REPLY" done < <(find . -name "*.txt") Why or when is one preferred over the other?
from the man bash, If no names are supplied, the line read is assigned to the variable REPLY. in your second attempt there is no name so it stores in the REPLY variable by default. example: $ cat infile 1 2 3 $ while read ; do echo $REPLY; done <infile 1 2 3 but it (REPLY variable) doesn't set when you specify a na...
Since read has a built in variable $REPLY, why do we need to explicitly state $line or other variable
1,590,801,567,000
I am trying to create a small script for creating simple, all-default Apache virtual host files (it should be used any time I establish a new web application). This script prompts me for the domain.tld of the web application and also for its database credentials, in verified read operations: read -p "Have you created...
How about a shell function? Like function read_n_verify { read -p "$2: " TMP1 read -p "$2 again: " TMP2 [ "$TMP1" != "$TMP2" ] && { echo "Values unmatched. Please try again."; return 2; } read "$1" <<< "$TMP1" } read_n_verify domain "Please enter the domain of your web application" read_n_verify ...
read-verification alternative (two prompts and if-then comparison alternative)
1,590,801,567,000
NOTE: st is the actual name of the terminal emulator in my question - https://st.suckless.org/. I want to create a shortcut that if pressed, pops up st and displays the translation of the word in the clipboard. I tried using this, but is exits immediately and gives an error: $ st -e "trans $(xclip -o) -t en; read"` c...
The -e option is a compatibility mechanism in simple terminal. The command and arguments that you pass, with or without -e, are executed directly, by simple terminal forking and then running execvp() in the child process on exactly the command and arguments it is given. There's no shell involved, and the arguments p...
Execute semicolon separated commands passed to the -e flag of st (Simple Terminal)
1,590,801,567,000
So I'm writing a script to basically run my docker applications from quickly, I've got everything working just fine it does everything I coded it to do. I just have a question about one of my functions: function prompt_user() { echo "Enter details for docker build! If it's a new build, you can leave Host Directory...
I'm not sure how much cleaner this is than your existing function but using an associative array (requires bash v4.0 or later) combined with a for loop you could use read once. function prompt_user() { declare -A prompt_questions vars=(IMAGE_NAME IP_ADDRESS PORT_ONE PORT_TWO CONTAINER_NAME NODE_NAME HOST_DIRE...
Using 'read' for more than one variable
1,590,801,567,000
My question is based on the following question/answer. I am trying to use the read -n 1 a solution as given there. However, FreeBSD gives me a : read: Illegal option -n I don't know how to find out, what the FreeBSD equivalent is. (Please don't tell me RTFM, I searched but can't find the proper info.
This is not dependent on your operating system but on your shell. In bash and ksh93, read -n N will read a specific number (N) of characters (or bytes). Other shells, such as dash or ash (which serves as sh on FreeBSD) and pdksh (which is sh and ksh on OpenBSD), does not have a read that has this option. The tcsh and ...
What is the FreeBSD equivalent of "read -n"?
1,590,801,567,000
Today I have learned some tricks about menu option in command line. One of these was cat << EOF Some lines EOF read -n1 -s case $newvar in "1") echo ""; ecsa It's really magical. I can't find any description in man page about this option. How the input to read command was pushed into case option ? It usually...
The documentation of read notes that: If no names are supplied, the line read is assigned to the variable REPLY. From that point it's a normal case statement. -n1 reads a single byte and -s turns off terminal echo of the input.
What does "read -n1 -s" mean in this script?
1,590,801,567,000
The following file runs, but not doing anything, yet it does not error.... while read dates; do ./avg_hrly_all_final.sh ${dates}; done < ./dates_all.csv I have a list of dates in "dates_all.csv" that have the following form: 2005 01 2005 02 2005 03 And the script I am calling "avg_hrly_all_final.sh" works by passin...
This is a likely job for xargs: printf %s\\n '#!/bin/sh' 'printf "<%s>\n" "$$" "$@"' >avg_hourly.sh chmod +x ./avg_hourly.sh xargs -n2 ./avg_hourly.sh <<\IN 2005 01 2005 02 2005 03 IN xargs will split on the spaces by default and invoke the specified command once per -n2 occurring arguments. I just wrote a little dum...
use "read" command to pass lines as positional parameters to a shell script
1,590,801,567,000
I wish to back up some of the files located in my home dir. That is simple files at the root of my home and some directories in my home, listed in ~/worthsaving.txt Sample worthsaving.txt: cloud work/web work/python I made this script : #!/bin/bash srce=/home/poor dest=/run/media/poor/backup mkdir -p $dest cp -v $...
There is a blank line in your list of files to backup. Inside the loop this means that $worth is empty, which in turn results in execution of this command: cp -Rv /home/poor /run/media/poor/backup/ In case it's not yet clear, this copies your entire home directory to the target directory poor in the destination. Here...
Why is my entire home backed up?
1,590,801,567,000
Now we're all familiar with not using: find . -print | xargs cmd but using find . -print0 | xargs -0 cmd To cope with filenames containing e.g. newline, but what about a line I have in a script: find $@ -type f -print | while read filename Well, I assumed it would be something like: find $@ -type f -print0 | while...
When using read, you can use just -d '' to read up to the next null character. From the bash manual, regarding the read built-in utility: -d delim The first character of delim is used to terminate the input line, rather than newline. If delim is the empty string, read will terminate a line when it reads a NUL charac...
reading filenames with newlines
1,590,801,567,000
in shell script when you have the following : read my_variable Enter is the key that saves your input. is there a way to make Tab accomplish the same as Enter without removing Enter's functionality?
It may be overkill but you could obtain that by using read -e, which enables the Readline facility on the read utility. At that point your desired result would be only one key-binding away. Careful though that Readline brings along many other functionalities too, like completion, history, etc., which you might not wan...
Shell script on "read" accept via both enter key and tab key
1,590,801,567,000
I am trying to read a password from user, i used -s silent flag but read -s is not working from the script but it works if i do it manually from terminal. error details project.sh: 3: read: Illegal option -s you entered code maddy@ElementalX:~/Desktop$ cat project.sh #!/usr/bin/sh read -s -p "Enter Password: " ...
The -s option to the built-in utility read is not a standard option, and is unlikely to be implemented in sh. Likewise, the -p option for giving a custom prompt is unlikely to be implemented by a generic sh. Run your script with bash instead, whose read does support -s for reading from the terminal without echoing th...
read -s gives error via script
1,590,801,567,000
Why when reading input with read, and the input is ??? the result is bin src? $ read ??? $ echo $REPLY bin src Running bash on macOS.
The data held in the variable REPLY is still ???, but the result from using the variable unquoted with echo, like you are doing, is the same as doing echo ??? You need to double quote all variable expansions. When you leave a variable expansion unquoted, two things happens: The value of the variable is split into mu...
read command with ??? input
1,590,801,567,000
I want to make the following script to prompt the user after each iteration, and wait for input before running the next iteration: #!/bin/sh DIR=$(pwd) for f in $DIR/test-data/*.txt do echo "$f" n=$(wc -w < "$f") k=$(( $n > 6 ? 6 : $n )) echo $n:$k java "Permutation" $k < "$f" read -p "Press ...
POSIX read doesn't have -p, that's a non-POSIX extension implemented in some shells (like bash). You're currently using /bin/sh which is probably a POSIX-compliant shell with limited extensions, if you want to use bash extensions you should consider using /bin/bash instead. Instead, you can POSIXly do this: printf 'Pr...
How do I get a user input inside a `for in` loop
1,590,801,567,000
I am using these commands in Linux Kali but I keep getting an error when I run the second command: "No such file or directory found." end=7gb read start _ < <(du -bcm kali-linux-1.0.8.amd64.iso | tail -1); echo $start parted /dev/sdb mkpart primary $start $end These are some commands out of a larger set of commands I...
read start _ This assigns the first word (according to $IFS) of the input line to the variable start. du -bcm kali-linux-1.0.8.amd64.iso | tail -1 is a strange way for getting the size of the file, rounded up to the next megabyte. parted /dev/sdb mkpart primary $start $end creates a partition on sdb which begins af...
What does these commands do?
1,590,801,567,000
In what way does the final value of number being assigned by read var number (and we enter 5) and number=5 differ? I was making this for loop: read var number #number=5 factorial=1 i=1 for i in `seq 1 $number` do let factorial=factorial*i done echo $factorial when I noticed that if the number has the value a...
If you change the first line to read number you’ll get the behaviour you’re looking for. read var number reads two values and stores them in variables named var and number. If you only input one value, seq 1 $number expands to seq 1 which is just 1.
For with read value
1,590,801,567,000
This post 'Output file contents while they change' is similar but the answer doesn't work for my case. Tail -f doesn't seem to refresh the output when the file's size doesn't change or when there are no new rows added. The file I'm trying to monitor/watch in SSH holds the value of a Volt Meter reading and it changes f...
If the filesize doesn't change then the file isn't being appended to, it's being overwritten. Depending on how the file is being rewritten, tail -F (capital F) may detect the change and rewrite it. Otherwise if the file is small (e.g. just one line) then something like while [ 1 ] do cat file sleep 2 done Will re...
Watch/View file contents but no new lines added
1,590,801,567,000
Is it possible to create a virtual file in unix, whose contents are determined programmatically when the file is accessed, a bit like the files in /proc? For example, I have a program that retrieves a particular setting by reading/catting a file. However, rather than store that setting directly in a plain text file, ...
You could look at Named Pipes. man fifo for a starting point. Essentially you create a named pipe, one process (or more) reads from it and another can write to it.
Creating a virtual file whose contents are determined programmatically [duplicate]
1,590,801,567,000
I have a script that looks something like the following. find /path -type f | sed -re 'stuff' | xargs -Ix sh -c '{ echo "information about x" ./exe < x read }' My goal is to provide each file given to xargs as input to exe. However, I do not want the output of exe to be provided all at once. Instead, I wish to ...
You can redirect the input to read from /dev/tty like this: read reply < /dev/tty You can accomplish effectively the same results within the shell, without using xargs and without directly executing a new shell to process each file: find /path -type f | sed -re 'stuff' | while IFS= read -r x do echo "information ...
Pause (with read or similar) in xargs
1,590,801,567,000
I have the following text file: (Employee Ashley) insert text here (Employee Bob) insert text here (Employee Joseph) insert text here I would like to take the text for each "employee" and save it to a new file. I can manually count the number of employees if that's necessary. How can I do this all from terminal...
awk ' /^\(Employee/ { FILENAME=""; for ( i=2 ; i<=NF; i++) FILENAME=FILENAME $i; FILENAME=substr(FILENAME,1,length(FILENAME)-1) ".txt"; } !/^\(Employee/ { print >> FILENAME } ' This presumes the first line will always be an ...
Saving data between names in terminal to new files?
1,590,801,567,000
How can I read in POSIX bash input like this: <name>,<tag1> <tag2> <tag3>… I tried while read line;do done but this wants newlines, all I have is spaces. (Is IFS solution? If yes, how? (I don't fully understand IFS.))
Use an array: echo '<name>,<tag1> <tag2> <tag3>' | while IFS=" ," read -a foo; do echo ${foo[@]}; done Output: <name> <tag1> <tag2> <tag3> From man bash: IFS: The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command.
Reading input fields separated by spaces
1,637,076,812,000
I am trying to direct user input file into while loop, but kept on failing when ran the script. The user input file genelist contained a list of numbers where I have been using as prefixes of my other files. Eg. 012.laln, 012.model. genelist: 012 013 025 039 109 . . . This is the script I have been testing on. #!/usr...
The errors have nothing to do with your loop. You are using read wrong: $ read -pr "genefile: " genelist bash: read: `genefile: ': not a valid identifier The -p option needs an argument, and you're giving it r as the argument if you use -pr. You need: read -p "genefile: " genelist or read -rp "genefile: " genelist ...
Read file from user input with a list of prefixes, then call file with prefixes in while loops
1,637,076,812,000
I've written a bash function that accepts a command as an argument, runs it in the background, and allows the user to kill the command by pressing any key. This part works fine. However, when I pipe it to a whiptail dialog gauge, the whiptail runs as expected, but after it returns, the terminal will no longer display ...
While this doesn't answer OP question, it can be useful for someone else landed here, looking for the fix/workaround. As NickD in his comment pointed out, whiptail sets -echo (in my environment not just echo). To fix your script you can put stty echo at the end of it. What your script (whiptail) changes you can see ...
No keyboard output on terminal after running a script using read and whiptail
1,637,076,812,000
I have a lab ntlm-extract.ntds file which has usernames and hashes in the format: domain\username:integer:hash:hash2 For example: somedomain.local\jcricket:5201:0020cfaecd41954fb9c9da8c61ccacd7:0020cfaecd41954fb9c9da8c61ccacd7 I'm comparing the hashes in the LINE[3]/hash2 column with hashes in the NTLM HIBP database, ...
You need -r on the outer read, not just on the inner read -a. You should also quote "${line}" and (probably) want IFS= unless you explicitly want to strip leading whitespace: while IFS= read -r line; do IFS=: read -ra LINE <<< "${line}"; printf '%s\n' "${LINE[@]}" done < ntlm-extract.ntds somedomain.local\jcricket ...
How to avoid losing my escape characters when reading in variables from a file with bash
1,637,076,812,000
I'm not good at bash and Linux. I'm reading a script and I found the following function. get_char() { SAVEDSTTY=`stty -g` stty -echo stty cbreak dd if=/dev/tty bs=1 count=1 2> /dev/null stty -raw stty echo stty $SAVEDSTTY } Basically, it is used to implement Press any key to continue featu...
The get_char function from the question has problems wrt keys which generate multibyte characters and with the fact that stty acts on the stdin but dd reads from /dev/tty[1], so I'll use a "fixed" and simplified version of it to do the comparison: get_char(){ _g=$(stty -g); stty raw -echo; dd count=1 2>/dev/null; st...
Is there any reason to use this custom read_char function instead of the builtin read command?
1,637,076,812,000
I have 2 text files "${LinkP}" and "${QuestionP}. I want to read these files and store each complete line in the respective array, IFS=$'\r\n' GLOBIGNORE='*' command eval "LinkA=($(cat "${LinkP}"))" IFS=$'\r\n' GLOBIGNORE='*' command eval "QuestionA=($(cat "${QuestionP}"))" Now I want to operate on these using a for...
store each complete line in the respective array is easy with a different approach: mapfile LinkA < "$LinkP" See help mapfile for more options, such as -t to remove a trailing delimiter from each line.
Reading multiple files and operating on stored Arrays
1,637,076,812,000
Let's say I defined this function in the script: fct1() { local msg1=${@} if [[ "${verb}" = 'tru' ]]; then echo "I say $msg1" sleep 1 echo "i repeat" sleep 1 echo "I saaaaaaaaay $msg1" else echo "$msg1" fi } How would I go about making a user call this function from read ? I'm thinking something like re...
If you wanted the message do be read as one line from stdin (entered by the user when the script is used in a terminal) and then passed as argument to the function, you could do: fct1 "$(line)" line is no longer a standard command but still fairly widespread. You could replace it with head -n1, but with some implemen...
Treating the input for the read command as a command itself
1,637,076,812,000
Can we use read(), write() on a directory just like on any other file in Unix/Linux? I have a confusion here because directories are also considered as files.
Some filesystems allow to use read() on directories, but this must be seen as a mistake since the data structures in such a directory may be undocumented. You never can use write() since this would destroy the integrity of the affected directory. The official interfaces for directories are opendir(), closedir() readdi...
Can we use read(), write() on a directory in unix/linux?
1,637,076,812,000
I have a script which guides users through the installation of my software and I want to write a log file in case something bad happens and the user needs support. The script looks like this: while true; do echo "This script will help you with the installation. Do you wish to proceed?" echo "(1) Yes" echo "(2) N...
You should use script instead, it’s designed for exactly this purpose: script /var/log/myinstall.log -c ./install.ksh It will log the input to read as well as any output.
Writing user input to file using tee
1,637,076,812,000
I am running several dedicated servers on different tmux sessions. I have to change ports and have to write a command in all the tmux sessions. The command is: config['Port'] = 12345, 12345 being the port. I tried to write a script which would take inputs from me and type the whole code with the code I input into all ...
Use double-quotes to expand variables in bash shell. What you done is passed avar as a literal string to tmux attach-session even though you have a value stored in the variable. Since single-quotes do not expand shell variables, you need prefix a $ before the variable name and double-quote it. Change your script to so...
Bash - Take input from user and send a command having that input in tmux
1,637,076,812,000
I need to create a bash script where a single argument is passed by the user (without using the "read" input option) at the terminal command line that creates a directory with that name, or otherwise notifies the user that such directory exists. Most of the script seems pretty straight forward, except for the input ...
a single argument is passed by the user (without using the "read" input option) at the terminal command line that creates a directory with that name, or otherwise notifies the user it exists... It sounds like ordinary positional commandline parameters are what you need: Script source code for mkdir1: #!/bin/sh mkdir...
Linux bash script input without using "read" [closed]
1,637,076,812,000
I've two documents: doc1.lst and doc 2.lst I want to take the content of each line and put it as parameters for my SQL query. I tried something like this, please correct me file=doc1.lst while read line do p1=$line; file=doc2.lst while read line do p2=$line; sqlplus64 $U...
As I understand it (the <<EOF2 stuff at the end isn't crystal-clear), the end result you're after is to feed the following into sqlplus64: @update.sql AAA 30 @update.sql ABC 10 @update.sql EDF 30 To produce this, instead of looping over the contents of both files, you can combine them. Using paste on both files (past...
Shell : while read line nested
1,637,076,812,000
I have a long line that comes as output from a git command: a=$(git submodule foreach git status). It looks like this: a = "Entering 'Dir1/Subdir' On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean Entering 'Dir2' HEAD detached at xxxxxx nothing to commit, working tr...
You can use readarray bash builtin and specify the delimiter within the same command: readarray -d 'char delimiter' array <<< $variable For example: readarray -d '@' array <<< ${a//Entering /@} Finally when you print each result you might want to remove the @ (or any other character used as delimiter): echo ${array[...
How to separate long string into a string array with IFS and read, or any other method
1,637,076,812,000
Hereafter are two read statements, one that uses a space as a delimiter, and the other \0. Only the first works. What am I doing wrong with the second? $ IFS=' '; read first second < <(printf "%s " "x" "y" ); echo "$first+$second" x+y $ IFS=$'\0'; read first second < <(printf "%s\0" "x" "y" ); echo "$first+$secon...
Try using an array, and the mapfile AKA readarray built-in. See help mapfile for details. If you provide an empty string as the argument to mapfile's -d option, it will use a NUL as the delimiter. First, create a function that can join an array into a single string with an arbitrary separator: $ joinarray() { local...
Splitting a null separated string
1,637,076,812,000
I'd like to show that entering passwords via read is insecure. To embed this into a half-way realistic scenario, let's say I use the following command to prompt the user for a password and have 7z¹ create an encrypted archive from it: read -s -p "Enter password: " pass && 7z a test_file.zip test_file -p"$pass"; unset ...
What's insecure is not read(2) (the system call to read data from a file). It isn't even read(1) (the shell builtin to read a line from standard input). What's insecure is passing the password on the command line. When the user enters something that the shell reads with read, that thing is visible to the terminal and ...
Sniff password entered with read and passed as a command line argument
1,637,076,812,000
I'm trying to create an interactive bash script, where i can call given options from 1-n or just them like commands. It will end up with a simulated prompt and 'read' is used to get the input, ofc. But, if i type too big of a text, it will return to the beginning of the line and overwriting the prompt as i type. Promp...
When reading from a terminal, bash uses the readline library when executing the read builtin. It also uses readline when inputting command lines. In order to handle line wrapping correctly, readline needs to know if any characters in the prompt string do not take up any space on the screen. If you were to call readl...
Input from readline owerwrites the prompt
1,637,076,812,000
I have a few hundred lines like below in connRefused.log:- 2015-12-12 00:12:10,227 ERROR [Testing-KeepAlive-01] c.v.v.v.Connection [Connection.java : 001] failed to bind to {name=TestGW,direction=BOTH_WAY,username=espada,password=whatever,binds=1,keepAliveInterval=60000,params={Payload=0, useEXP=1},thisOne={id...
You don't need to use an array. Since the input data appears to be very regular, I would convert the input data into shell assignment statements, then read them into the shell and evaluate. Like this: #!/bin/sh sed ' s/^[-0-9]* */date=/ s/,.*thisOne={/ / s/}.*// s/,/ /g ' "$@" | while read line do ...
Extract fields of a line into shell variables
1,637,076,812,000
My process deadlocks. master looks like this: p=Popen(cmd, stdin=PIPE, stdout=PIPE) for ....: # a few million p.stdin.write(...) p.stdin.close() out = p.stdout.read() p.stdout.close() exitcode = p.wait() child looks something like this: l = list() for line in sys.stdin: l.append(line) sys.stdout.write(str(len...
parent.py from subprocess import Popen, PIPE cmd = ["python", "child.py"] p=Popen(cmd, stdin=PIPE, stdout=PIPE) for i in range(1,100000): p.stdin.write("hello\n") p.stdin.close() out = p.stdout.read() p.stdout.close() print(out) exitcode = p.wait() child.py import sys l = list() for line in sys.stdin: l.append...
Deadlock on read/wait [closed]
1,637,076,812,000
I would like to read a password from stdin, suppress its output and encode it with base64, like so: read -s|openssl base64 -e What is the right command for that?
The read command sets bash variables, it doesn't output to stdout. e.g. put stdout into nothing1 file and stderr into nothing2 file and you will see nothing in these files (with or without -s arg) read 1>nothing1 2>nothing2 # you will see nothing in these files (with or without -s arg) # you will see the REPLY var ha...
Read from stdin and pipe to next command
1,637,076,812,000
How can i read list of server entered by user & save it into variable ? Example: Please enter list of server: (user will enter following:) abc def ghi END $echo $variable abc def ghi I want it to be running in shell script.If i use following in shell script: read -d '' x <<-EOF It is giving me an error : line 2: w...
You can do servers=() # declare an empty array # allow empty input or the string "END" to terminate the loop while IFS= read -r server && [[ -n $server && $server != "END" ]]; do servers+=( "$server" ) # append to the array done declare -p servers # display the array This also ...
Read list of servers for user?
1,637,076,812,000
I have a list of commands to parse through for an audit, similar to this: 1. -a *policy name=PolicyName -a *policy workflow name=PolicyWorkflow -a *policy action name=PolicyAction -s Server -b Storage -J Node -y 1 Months -o -F -S 2. -a *policy name=PolicyName -a *policy workflow name=PolicyWorkflow -a *policy action n...
In bash and using an array variable instead, you can do something like: { IFS=$'\n'; array=($(grep -Po 'name=[^-]+(?=\s*-)' infile)); } then print the elements of the array (array Index in bash starts from 0): printf '%s\n' "${array[@]}" name=PolicyName name=PolicyWorkflow name=PolicyAction name=PolicyName name=Polic...
Bash script Issue parsing text in line with whitespace characters
1,637,076,812,000
I am reading the content of a file do.sh using the bash command line structure. I want to execute each line of this file, line by line, so that, later, I can add some text to the script which can handle the failure of any of the in-between lines and stop the execution of afterwards content. The syntax I am using for ...
Sourcing the dot-script using either the standard . ./do.sh or non-standard source ./do.sh ... would have solved the original question, which only asked about a way of executing the script and leaving the created variables in the current environment (and creating the file containing the output of ls). The updated qu...
Read from file; and execute its content line by line; terminate at first error [closed]
1,637,076,812,000
In bash manual, about read builtin command -d delim The first character of delim is used to terminate the input line, rather than newline. Is it possible to specify a character as delim of read, so that it never matches (unless it can match EOF, which is a character?) and read always reads the entire of a file at ...
Since bash can't store NUL bytes in its variables anyway, you can always do: IFS= read -rd '' var < file which will store the content of the file up to the first NUL byte or the end of the file if the file has no NUL bytes (text files, by definition (by the POSIX definition at least) don't contain NUL bytes). Another...
Is there a character as `delim` of `read`, so that `read` reads the entire of a file at once?
1,517,797,791,000
I have this read operation: read -p "Please enter your name:" username How could I verify the users name, in one line? If it's not possible in a sane way in one line, maybe a Bash function putted inside a variable is a decent solution? Name is just an example, it could be a password or any other common form value. ...
That the user typed (or, possibly, copied and pasted...) the same thing twice is usually done with two read calls, two variables, and a comparison. read -p "Please enter foo" bar1 read -p "Please enter foo again" bar2 if [ "$bar1" != "$bar2" ]; then echo >&2 "foos did not match" exit 1 fi This could instead be ...
One line read verification [closed]
1,517,797,791,000
This is simple #!/bin/bash echo "What is your name?" read name echo "Your name is: $name" But what if I don't want to treat a name but a large HTML code block with nested tags and all their special characters? (a block that will be interactively pasted) How can i save an entire html code block into a variable with a ...
Instead of reading a line with read you can read directly from the input with cat. This will read from stdin (typically the terminal if you type it directly at the prompt) and write to stdout (also the terminal). Use Ctrl/D to end your input: cat In the more general case the cat command reads from one more files list...
Bash: interactively enter and save large html block into a variable from the terminal
1,517,797,791,000
In one directory, I have several PNGs and one text file. The PNGs are named after UPC barcodes, like 052100029962.png, 052100045535.png, etc., and I have one text file upcs.txt where each line contains the UPC code merged with product name, like so: ... 052100029962mccormickpepper 052100045535mccormickonesheet ... I ...
You have to use a delimiter for a file containing two fields per row. Here a sed inserts this delimiter and the result is given line by line to mv #!/bin/bash while read -r oldname newname; do [ -f "${oldname}.png" ] && echo mv -- "${oldname}.png" "${newname}.png" done < <(sed 's/^[0-9]*/& /' upcs.txt) Remove ech...
change filename based on current filename matched with separate file content
1,517,797,791,000
I wrote a script that collects application logs on local machine and then from remote machine. It has variable oldlogsdate which reads the date of logs I want to collect. For example, if I enter Apr 23 it works fine because there is only one space, but if I enter Apr 4 (two spaces between Apr and 4) it will remove on...
Read command removes double space and Keeps only one It doesn't. The read command by itself keeps the interior whitespace as is (however it will trim leading and trailing whitespace unless you set IFS to empty; it also will mangle backslashes if you don't use -r). read myVar <<<'Apr 4' echo "$myVar" # will output:...
Read command removes double space and keeps only one
1,517,797,791,000
I have the following bash script that I'd like to use as a fuzzy file opener. I create a fifo, spawn a new terminal with fzf running and redirect fzf's output to the fifo. I then call a function that reads from the fifo and opens the files. My problem is that the while loop inside the open function never ends. How can...
I would suggest a couple of alternatives, because: based on the script in your question, a FIFO seems actually not needed; in principle, since you are using Bash, you could take advantage of the NUL character as a delimiter (the only byte that is not allowed in a POSIX file path); unfortunately, though, fzf does not ...
How can I read from named pipe line by line and exit?
1,517,797,791,000
#!/bin/bash echo -n "Enter a number >" read number for var in $number do read number echo $var done echo "Go!" I want numbers from 8-1 to print vertically and say go at the end. When I run the code only 8 and Go! prints out.
Use seq: #!/bin/bash echo -n "Enter a number > " read number seq "$number" -1 1 echo "Go!" Output: Enter a number > 8 8 7 6 5 4 3 2 1 Go! To improve your code a bit, you could output the prompt to stderr: >&2 echo -n "Enter a number > " or use the -p option from read: read -p 'enter a number > ' number
Using for loop with read command
1,517,797,791,000
For example, the user types foofoo\b\b\bbar, presses enter and gets a var equaling foofoo\b\b\bbar instead of foobar. Yes, the user loses the deletion feature so they need to use another shortcut for deletion. Or at least the other way around: normal backspace (pressing) gives them foobar and some modifier + backspace...
This script (in bash) will accept any character except ^C (ASCII 03 ETX ) ^J (ASCII 0A LF ) ^M (ASCII 0D CR ) ^Z (ASCII 1A SUB ) ^\ (ASCII 1C FS ) including all other control characters: #!/bin/bash while IFS= read -srn1 a ;do [[ "${a+x$a}" = "x" ]] && break var=$var$(printf '%s' "$a") printf '%s' "...
(How) can I get `read var` to add the literal \b (backspace) to var?
1,517,797,791,000
I am trying to create a while loop so that it takes content from one file and creates some content on another file. But what i noticed is that it is only creating the last line of the file instead of all the lines in the file. What am i missing here? Or is my approach with echo wrong? My file called "test" contains a ...
In Bash, the > operator intentionally overwrites any existing data in the file, while the >> operator will append. If you need to make sure the file is empty before you start, you can use printf "" > myfile.json to clear it out before your loop runs, then use >> to continue writing to the end.
Trying to create a while loop to output content of one file to another
1,517,797,791,000
I need to read PCI device information from files. But it gives unusable output when I use command like that: cat /proc/bus/pci/05/00.0 Output: �h�� How could I fix this? OS: Debian-like Linux x64, Kenel 4.19
Not every file under /proc/ contains text. /proc/bus/pci/05/00.0 (and similar files) contain binary data, not text. They're not meant to be displayed to a terminal, they're meant to be read by a program that understands the binary data format (which will be documented somewhere in the kernel documentation. or source ...
Listing PCI Devices By Reading From File (Instead of lspci Command)
1,517,797,791,000
I'm trying to read a list of files from a command and ask the user for input for each file. I'm using one read to read the filenames, and another one to get user input, however this script seems to enter an infinite loop. foo () { echo "a\nb\nc" | while read conflicted_file; do echo $conflicted_file while tru...
read reads from stdin, so both of those reads there will read from the output of echo via that same pipe open on their stdin. For the read inside the loop to read from the stdin outside the pipe, you could do: foo () { printf 'a\nb\nc\n' | while IFS= read -r conflicted_file; do printf '%s\n' "$conflicted_f...
Nested read statement leads to infinite loop in bash
1,517,797,791,000
I have a file that has a list of bash commands like the following: echo 'foobar' echo 'helloworld' echo 'ok' And I can execute these commands by simply piping them to /bin/bash like so: cat commands | /bin/bash Now, how do I pause the execution right in the middle, and wait for the user input? Using read does not se...
Execute like this: /bin/bash commands Piping the file to bash makes the file travel via stdin of bash. In such case read, reading from stdin, reads from the piped stream instead of from the terminal. It consumes echo 'ok'. By specifying the file as an argument to bash you still execute it, this time the stdin is not...
Pause execution of a list of commands
1,517,797,791,000
I wish to send a command to process A, from process B, via a FIFO. The command will be a word or a sentence, but wholly contained on a "\n" terminated line - but could, in general, be a multi-line record, terminated by another character. The relevant portion of the code that I tried, looks something like this: Proce...
Yep, that's exactly what happens: $ mkfifo p $ while :; do cat p ; done > /dev/null & $ strace -etrace=open,close bash -c 'echo -n foo > p; echo bar > p' |& grep '"p"' -A1 open("p", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3 close(3) = 0 -- open("p", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3 close(...
bash: Reading a full record from a fifo
1,517,797,791,000
I have a script that joins together various lists of data fields which then needs to have a few more columns added. The file generated looks like this: $ cat compiled.csv "name":"Network Rule 1", "description":"Network Rule 1", "from":["internal"], "source":["any"], "user":["domain\\network_user1"], "to":["external"],...
read by default interprets backslashes that can be used to escape IFS characters from delimiting, the -r option turns that off. $ read a b <<< '1\ 2 3' $ printf "<%s>\n" "$a" <1 2> $ read -r a b <<< '1\ 2 3' $ printf "<%s>\n" "$a" <1\> Also, even with just one variable name given, read will remove leading and trail...
Double backslash disappears when printed in a loop
1,517,797,791,000
While trying to learn how to manipulate the content of files in bash, I encountered the following code example: while IFS=, read -r col1 col2 do echo "I got:$col1|$col2" done < myfile.csv According to The Open Group Base Specifications Issue 6: The read utility shall read a single line from standard input. If m...
For the purposes of redirection in this example, stdin for everything in the while loop, including the conditional, will be myfile.csv You could redirect it as you suggest, but then the redirection would be set up separately for each call to read, and it would just read the first line every time.
How does "done < file" work in a while loop?
1,517,797,791,000
The following script is meant to trim all media files in the current working directory. #!/usr/bin/bash trimmer() { of=$(echo "${if}"|sed -E "s/(\.)([avimp4kvweb]{3,3}$)/\1trimmed\.\2/") ffmpeg -hide_banner -loglevel warning -ss "${b}" -to "${ddecreased}" -i "${if}" -c copy "${of}" echo "Success. Exiting .." } ...
Your code is essentially doing the following: foo () { read variable } while read something; do foo done <input-file The intention is to have the read in foo read something from the terminal, however, it is being called in a context where the standard input stream is redirected from some file. This means tha...
Why does the execution of these functions break out of this while loop?
1,517,797,791,000
Hello I am learning Scripting here. I am trying to write a simple script using the 'for' loop. I have hundreds of folders in a folder called user. if i run this command i get a list of folders that i need to move to another folder cat failed | awk -F ":" '/FAILED/ {print $1}' | uniq i.e folders under users that have...
With GNU xargs and a shell with support for ksh-style process substitution, you can do: xargs -rd '\n' -I USER -a <(awk -F : '/FAILED/ {print $1}' failed | sort -u ) cp -r users/USER user/failed/USER With zsh, you could do: faileduser=( ${(f)"$(awk -F : '/FAILED/ {print $1}' failed | sort -u)"} ) autoload zargs zar...
Looping through variables which is an output of another command
1,517,797,791,000
I have the following command in a linux script. #!/bin/bash for i in "001 ARG1" "002 ARG2" "003 ARG3" do set -- $i echo $1 echo $2 done 001 and ARG1 are essentially tuples, Is there a way to move those tuples into a text file which I can load instead into the forloop? so many i would save a text file lik...
Given two space or tab separated words on each line in a file as in your second example of the input file: while read -r word1 word2; do echo "$word1" echo "$word2" done <textfile.txt This would read the first word on each line into $word1, and the rest of the line into $word2. The input for read is given by ...
Iterating through a list of tuples or names from a text file
1,517,797,791,000
This command: read -d 'z' a < <(printf 'a\n\n\n'); printf "$a" outputs: a bash's read removes excess trailing newlines which is expected. and by changing the IFS to null character: IFS= read -d 'z' a < <(printf 'a\n\n\n'); printf "$a" it outputs: a (blank line) (blank line) read no longer removes the excess trailin...
Field splitting specifically ignores leading and trailing IFS whitespace. From the GNU Bash manual, 3.5.7 Word Splitting: If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions ...
why bash read doesn't remove excess trailing IFS characters
1,517,797,791,000
While studying bash process substitution, I found this: counter=0 while IFS= read -rN1 _; do ((counter++)) done < <(find /etc -printf ' ') echo "$counter files" If I understand correctly, the output of find command substitutes the "_". However: Which mechanism is this? Additionally: what does read -rN1 do? Up...
<(find /etc -printf ' ') is called "process substitution". It will generate one character (an space ' ') per each file. The output of find /etc -printf ' ' is made available in a file (or something that appears as a file). The name of this file is expanded on the command line. The additional < performs the redirection...
Is this bash argument substitution?
1,517,797,791,000
Sometimes it's convenient to use read -t 3 instead of sleep 3. How do I make it work with nohup? nohup bash -c ' date; read -t 3; date ' | tail -n 2 nohup.out As you can see, read -t 3 does not wait for three seconds.
read -t 3 (a ksh93 extension now also supported by zsh, bash and mksh) is meant to read one line (logical line in that lines may be continued with a trailing backslash as you don't use the -r option) from stdin into $REPLY with a 3 second timeout. If stdin is a terminal, that will sleep for 3 seconds unless the user p...
Sometimes it's convenient to use ` read -t 3 ` instead of ` sleep 3 `. How do I make it work with `nohup`?
1,517,797,791,000
I have a file with the following values. I am trying to read from the file and add 1096 to the last value and generate the output on screen. My original file looks like this. agile_prod_toolkit,30 alsv2_prod_app,30 alsv2_qa_app,15 My expected output should be as below. the third value is second value + 1096 agile_pr...
value=$ret+1095 is not an arithmetic assignment, and the bash shell has no print (perhaps you meant printf?). You could do while IFS=, read -r line ret; do let value=$ret+1095 echo "$line,$ret,$value" done < final_original or with the more modern arithmetic syntax and printf while IFS=, read -r line ret; do v...
Add a numerical value to a variable while reading a file in bash in loop [duplicate]
1,517,797,791,000
I am developing a zsh script that uses read -k. If I execute my script like this (echo a | myscript), it fails to get input. Apparently it is due to the fact that -k uses /dev/tty as stdin invariably, and you must tell read to use stdin as in read -u0. But then if I change it to -u0 (which makes previous case work) an...
read -k (read N characters) and read -q (read y or n) have two modes of operation: By default, they read from the terminal. They put the terminal in raw mode to read byte by byte (as many times as necessary to read the requested number of characters) rather than line by line. They can be instructed to read from an ex...
Issue of read with -u and -k in zsh
1,517,797,791,000
I'm trying to read remote SSHD server version with bash without installing an extra tool : $ cat < /dev/tcp/x.y.z.t/22 SSH-2.0-OpenSSH_7.2 FreeBSD-20160310 ^C CTRL+C is needed, so I tried to read only one line but something strange happens in the output : $ read version < /dev/tcp/x.y.z.t/22 $ echo "=> version = $ver...
The IFS variable can be (locally!) modified to also include \r. This code probably needs more error checking on the arguments and perhaps some thought on how to handle timeouts or other such network issues. function read-ssh-version { local IFS=$'\r\n' read version < /dev/tcp/"$1"/"$2" echo "$version" } Some...
How to "properly" read remote sshd server version with bash
1,517,797,791,000
I'm binding a function of mine to hotkey: bind -x '"\em": __my_function' I would like the function to behave differently depending on if the command line prompt already contains characters or not. E.g. $ ***presses ^M*** behaves differently than $ cd ***presses ^M*** since a command/some text has already been typed ...
__my_function should check if $READLINE_LINE is empty or not. Example: __my_function() { if [ "$READLINE_LINE" ]; then echo foo else echo bar fi } Search for READLINE_LINE and READLINE_POINT in man 1 bash.
How to verify if current command prompt contains already-typed characters
1,517,797,791,000
In Bash, the following command echo foo | while read line; do echo $line; done outputs foo; however, the following alias bar="echo foo | while read line; do echo $line; done" bar outputs a \n (or empty space). What is causing this difference in behavior?
Use single quotes to defer variable expansion: alias bar='echo foo | while read line; do echo $line; done'
while read loop not working inside alias [duplicate]
1,517,797,791,000
I am with CentOS 7 and I want to bind an alias to launch PostgreSQL shell(psql). I defined this alias and append it in /etc/profile.d/alias: alias psql-local="read -p \"PSQL: enter the DB to connect: \" db ; sudo -i -u postgres psql --dbname $db" It is executable by root. And, I login as root, and run alias, I get: ...
Because you're using double-quotes ("..."), the $db variable will be expanded when you define the alias, not when it's used. Try this instead: alias psql-local='read -p "PSQL: enter the DB to connect: " db ; sudo -i -u postgres psql --dbname "$db"'
set alias to read variable and then use in second command; only works when I execute them manually
1,517,797,791,000
I have a file that contains something like the following: red dog red cat red bird red horse blue hamster blue monkey blue lion pink pony pink whale pink pig pink dolphin I need to increment a counter for every color, and then for every animal. So red would be 1, blue 2, pink 3. Next, dog, cat, ...
Something like this with awk: $ awk '$1 != c { cc++; c=$1; ac=0; a="" } $2 != a { ac++; a=$2 } { printf("%d.%d\n", cc, ac) }' file 1.1 1.2 1.3 1.4 2.1 2.2 2.3 3.1 3.2 3.3 3.4 The awk script keeps track of four things: The most recently read animal name, a. The most recently read colour, c. The "animal counter", ac. ...
Reset counter when change occurs while reading
1,517,797,791,000
I have this idea and maybe it is not feasible, but I think it worth asking. Let's say a user is running this command: cat ~/file.txt Whenever something tries to read from this file, I would like to run a script or command in the background instead and return the response of that script as content. Somehow like doing...
What you're looking for is possible, but perhaps not exactly as you envision. The way I have seen it done most often (and it is admittedly a very rare occurrence) is to create the file being read a named pipe (aka FIFO) special file, using the mknod command: mknod file.txt p You would then need to start the script yo...
Run a command which returns a string when reading a file [duplicate]
1,517,797,791,000
I want to do something with user input to use in grep. Like, instead of uin="first\nsecond\n" printf $uin | grep d which outputs second, I want to have the user input it, like read uin where the user could input "first\nsecond\n". Then the variable could be used in the grep line like above. Or if the user could inpu...
You could do: echo>&2 "Please enter a multiline string, Ctrl-D, twice if not on an empty line to end:" input=$(cat) printf 'You entered: <%s>\n' Note that $(...) strips all trailing newline characters, so that can't be used to input text that ends in newline characters. To read exactly two lines, just call read twice...
How to catch newlines in user input
1,517,797,791,000
Consider: $ read -r a <<<$(echo "foo"; exit 1) $ echo $? 0 this returns 0, when I really expect a 1. How can I extract the real exit code from the subshell?
You'll need multiple steps: output=$(echo "foo"; exit 1) status=$? read -r a <<<"$output" # assuming the "real" code here is more complex
How to capture subshell exit code when assigning subshell output to read? [duplicate]
1,517,797,791,000
Suppose I have log.txt The sample of log.txt are like these format: Code Data Timestamp ... C:57 hello 1644498429 C:56 world 1644498430 C:57 water 1644498433 ... If I want filter string line that contain C:57 I can achieve it with cat log.txt | grep C:57 then I redirect output to the new file hence cat log.txt | grep...
You can use tail -f thusly: tail -f log.txt|grep C:57 >> filtered_log.txt This continuously reads log.txt grepping for the token C:57 and adding any matches to the filtered.log.txt. The use of cat to read the log and pipe that to grep is a useless use of cat. grep can directly read a file. You're wasting I/O by combi...
Filter changing file periodically and redirect filtered output to new file
1,517,797,791,000
I have a question about how to read my file correctly in UNIX, I have the file given (attached as image) and this file has tabs between the variables, as you can see Blood is a variable and Whole Blood is another one. However, when I write in the terminal gawk '{print $7}'file.txt | head the result is the other attach...
The variable Input Field Separator defaults to all kinds of spaces. You want it to explicitly set it to a tab. The man page of awk says: -F sepstring Define the input field separator. This option shall be equivalent to: -v FS=sepstring And further down: FS Input ...
How to read my file correctly?
1,517,797,791,000
I am trying to use read command with wget, for that I am using a simple .sh script: # echo "Please answer by : -> yes <- or -> no <-" # read answer # echo $answer This code works fine locally, but the read command failed remotely with wget, it finishes without waiting an answer: # wget -qO - 'https://testserver/pub/t...
When you run your script with bash in the terminal, bash gets your standard input (you only have one) from the keyboard. keyboard -> script When you feed the script to bash over a pipe, that pipe becomes the standard input. So your problem is not related to wget, if you did this: cat test.sh | bash -x you'd have the...
Read command works locally and fail with wget
1,583,510,638,000
i need to create a bash that get input from user and insert them into an array until user enter an specific thing. for example, if i run script: enter variables: 3 4 7 8 ok i get this array: array=( 3 4 7 8 ) or: enter variables: 15 9 0 24 36 8 1 ok i get this array: array=( 15 9 0 24 36 8 1 ) how i can achie...
With newline as the default separator: read -a array -p "enter variables: " If you want a different character than newline, e.g. y: read -a array -d y -p "enter variables: " You can only use a single character as delimiter with read. EDIT: A solution that works with the ok delimiter: a= delim="ok" printf "enter vari...
read user input into array until user enter specific entry
1,583,510,638,000
I want to get user prompted date files which are in two different locations and scp to another server. This is what I have done so far, I am struggling with reading constants from file and conditioning with if condition . path1 (/nrtrdepath/) has 1 file path2 (/dcs/arch_05/AUDIT_REPORT/SL_AUDIT_REPORT/) 2 files ...
It looks like what you want to do is pick three file based on a date string and scp these to another location. This may be done with #!/bin/sh thedate="$1" scp "/nrtrdepath/AuditReport_SL_nrtrde_$thedate.csv" \ "/dcs/SL_AUDIT_REPORT/AuditReport_SL_ICT_$thedate.csv.gz" \ "/dcs/SL_AUDIT_REPORT/AuditReport_SL_...
Read a file line by line and if condition is met continue reading till end
1,583,510,638,000
I am running a benchmark of HDD read that bypasses page cache. I have set O_DIRECT flag and memaligned my memory. This function attempts a random read within a file(lseek64() used). The data I am getting looks fine until certain point (32 MB). Please see the data below (averages): In particular I would like to know wh...
The time to read a sector depends on the rotation angle of the drive when you try the read, and your sample size is too small to avoid statistical fluctuations from this random process. You're reading every sector just once on average. That's fine when bytes is large and you are taking a lot of samples, but not so gre...
read() randomly a file with O_DIRECT flag on, getting a serious performance hit on 32 MB files size?
1,583,510,638,000
I have simple script #!/bin/bash SENTENCE="" while read word do SENTENCE="$SENTENCE $word" done whose interaction with the user may result in the following: a a b a b c a b c d a b c d How can I have the string displayed at the right in the same line as the user in order to have the output a ...
Assuming the simplest case (a short word, no line-wrapping, no concern about reaching the end of the screen with scrolling), you could do this #!/bin/bash SENTENCE="" tput sc while read word do SENTENCE="$SENTENCE $word" tput rc tput hpa 20 printf '%s\n' "$SENTENCE" tput sc done That uses two term...
How to display a string at the right of the user insert prompt
1,583,510,638,000
I need to make a shell script that will receive a number of rows and a number of columns and then print a word as the number of rows and columns. For example: 2 rows, 3 columns expected output: word word word word word word I know how to use read but I don't know how to get the output.
This should put you on track : wordToPrint='hello' echo "How many rows?" read nbRows echo "How many columns?" read nbColumns for ((row=0; row<$nbRows; row+=1)); do for ((column=0; column<$nbColumns; column+=1)); do echo -en "$wordToPrint\t" done echo done
How to read numbers of rows and columns and print in a specific way
1,583,510,638,000
I have a txt file with content as such: Adedunmola Okikiola Adewole 512.035 215−39 ^M Ademir Cleto de Oliveira 055.735 445−13 ^M Adilson Wagner Gandu 559.995 780−28 ^M When I run my script, #!/usr/bin/bash file="$@" ...
The problem was that I was using - on grep, when the text was actually other character (which get's converted when I paste it to stack overflow)
Unable to match a specific regex with bash
1,583,510,638,000
I am having issues understanding how to get read to "read" information from the console instead of user input. Effectively "getline"? from console. Here is my scenario. I will be sending an echo "information" | ncat "IP" "PORT" to a port located internally on the network running a deamon to catch correct information. ...
I'm afraid your syntax is all wrong. I think you are looking for something like this: if [ "$line" = "Information wrong try again!" ]; then echo "Try again" else echo "All's well" fi Of course, the details will depend on how you run the script. If you want it to be an infinite loop and re-run the echo "informat...
Using a BASH script to read the output displayed in console from a third source?
1,583,510,638,000
I have a bash script that I wrote to automate some commands, and one of the first lines in the script isn't working on the computer that it needs to run on. The code is below #!/bin/bash #some comments read -p 'press enter to begin' echo "Please Wait..." #rest of the script It is a fairly simple start to the automa...
I figured out why the script was breaking, when using the read command I had read -p 'prompt' Instead of read -p "prompt" When I changed it to the double quotes the script ran fine for the beginning part that I was asking about in this question. Why did this specific format break the script? Idk, the machine I'm run...
Read command in bash script not executing as a read command and outputting text straight to command line [closed]
1,583,510,638,000
I am trying to get a folder name from a stored variable string. When I ran the following path="Folder%20Name/Dir/File" read -d "/" folder < <(echo ${path/\%20/ }) echo "$folder" I am getting a blank echo $folder. Where am I going wrong, I have tried read -d "/" folder <<< $"(${path/\%20/ })" with no sucess
Your first command works just fine on Bash 4.4: $ path="Folder%20Name/Dir/File" $ read -d "/" folder < <(echo ${path/\%20/ }) $ echo "$folder" Folder Name Though using process substitution here is unnecessary, you could just use a here-string instead: $ read -d "/" folder <<< "${path/\%20/ }" As for your second comm...
Why does read from variable give blank new variable? [closed]
1,583,510,638,000
Could someone perhaps give their advice on this. I am wanting to take an output file from a mysql query ran: $code $IP 123456 192.168.26.176 10051 192.168.20.80 234567 192.168.26.178 and run it in command: rsync -rvp *.$code.extension root@$IP:/path/of/dest I am trying this: while read -r line ; do echo "...
I can't see the result of your mysql query but you can execute it and parse with awk to print just what you want (see mysql option to avoid printing tuples and titles -raw or something like this ) mysql -printingoptions "your query" |awk '{print "rsync -rvp *."$1".extension root@"$2":/path/of/dest"}' You can pipe i...
Read variables in output file & rsync
1,583,510,638,000
The file to read is file.sql containing following text create table temp (name varchar(20), id number) on commit reserve rows; create table temp1 (name varchar(20), id number) on commit reserve rows; select name, id from temp where id=21; I want the three queries stored in three different files as below fi...
re='create table' csplit -s -k -f file. yourSqlFile "%^$re%" "/^$re/" '/^select name,/' '/./' for f in file.[0][0-3]; do k=${f#*.0} mv "$f" "file$k.sql" done for i in {2,1,0};do j=$((i + 1)) mv "file$i.sql" "file$j.sql" done
Read a text file and its store contents into different files or variables
1,344,375,382,000
I know you are able to see the byte size of a file when you do a long listing with ll or ls -l. But I want to know how much storage is in a directory including the files within that directory and the subdirectories within there, etc. I don't want the number of files, but instead the amount of storage those files take ...
Try doing this: (replace dir with the name of your directory) du -s dir That gives the cumulative disk usage (not size) of unique (hards links to the same file are counted only once) files (of any type including directory though in practice only regular and directory file take up disk space). That's expressed in 512...
How to recursively find the amount stored in directory?
1,344,375,382,000
I'd like to write something like this: $ ls **.py in order to get all .py filenames, recursively walking a directory hierarchy. Even if there are .py files to find, the shell (bash) gives this output: ls: cannot access **.py: No such file or directory Any way to do what I want? EDIT: I'd like to specify that I'm not...
In order to do recursive globs in bash, you need the globstar feature from Bash version 4 or higher. From the Bash documentation: globstar    If set, the pattern ** used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only di...
Recursive glob?
1,344,375,382,000
I want to see how many files are in subdirectories to find out where all the inode usage is on the system. Kind of like I would do this for space usage du -sh /* which will give me the space used in the directories off of root, but in this case I want the number of files, not the size.
find . -maxdepth 1 -type d | while read -r dir do printf "%s:\t" "$dir"; find "$dir" -type f | wc -l; done Thanks to Gilles and xenoterracide for safety/compatibility fixes. The first part: find . -maxdepth 1 -type d will return a list of all directories in the current working directory.  (Warning: -maxdepth is a GNU...
How do I count all the files recursively through directories
1,344,375,382,000
I am working through SSH on a WD My Book World Edition. Basically I would like to start at a particular directory level, and recursively remove all sub-directories matching .Apple*. How would I go about that? I tried rm -rf .Apple* and rm -fR .Apple* neither deleted directories matching that name within sub-directori...
find is very useful for selectively performing actions on a whole tree. find . -type f -name ".Apple*" -delete Here, the -type f makes sure it's a file, not a directory, and may not be exactly what you want since it will also skip symlinks, sockets and other things. You can use ! -type d, which literally means not d...
How do I recursively delete directories with wildcard?
1,344,375,382,000
I made a backup to an NTFS drive, and well, this backup really proved necessary. However, the NTFS drive messed up permissions. I'd like to restore them to normal w/o manually fixing each and every file. One problem is that suddenly all my text files gained execute permissions, which is wrong ofc. So I tried: sudo chm...
If you are fine with setting the execute permissions for everyone on all folders: chmod -R -x+X -- 'folder with restored backup' The -x removes execute permissions for all The +X will add execute permissions for all, but only for directories. See Stéphane Chazelas's answer for a solution that uses find to really not ...
How to recursively remove execute permissions from files without touching folders?
1,344,375,382,000
When I try to use sftp to transfer a directory containing files, I get an error message: skipping non-regular file directory_name The directory contains a couple of files and two subdirectories. What am I doing wrong?
sftp, like cp and scp, requires that when you copy a folder (and its contents, obviously), you have to explicitly tell it you want to transfer the folder recursively with the -r option. So, add -r to the command.
Using sftp to Transfer a Directory?
1,344,375,382,000
When I use cp -R inputFolder outputFolder the result is context-dependent: if outputFolder does not exist, it will be created, and the cloned folder path will be outputFolder. if outputFolder exists, then the clone created will be outputFolder/inputFolder This is horrible, because I want to create some installatio...
Use this instead: cp -R inputFolder/. outputFolder This works in exactly the same way that, say, cp -R aaa/bbb ccc works: if ccc doesn't exist then it's created as a copy of bbb and its contents; but if ccc already exists then ccc/bbb is created as the copy of bbb and its contents. For almost any instance of bbb this...
How to copy a folder recursively in an idempotent way using cp?
1,344,375,382,000
How can I search a wild card name in all subfolders? What would be the equivalent of DOS command: dir *pattern* /s in *nix?
You can use find. If, for example, you wanted to find all files and directories that had abcd in the filename, you could run: find . -name '*abcd*'
How can I search a wild card name in all subfolders?