New answers tagged

0

In regards to the bash shell I find the best way to remember is by understanding what is happening. If all you want to do is remember how to get the command correct, you might try program > /results 2> /results That's nice and obvious whats going on and easy to remember. i.e. 1 STDOUT is going to /results 2 STDERR is also going directly to ...


2

Enclose your script in something like : while true do ... your script here done You already have an exit condition, so this should work. If it is not, please indicate how it is failing


2

Just include LOCAL_PATH in pattern part: printf '%s\n' "${LINE//$LOCAL_PATH/}" If LINE always start with content of LOCAL_PATH, POSIXly: printf '%s\n' "${LINE#$LOCAL_PATH}"


3

factor {2..1000} | awk 'NF==2{print $2}'


0

Maybe it's the stdout buffer that's delaying the output. The pipe buffer may be quite large, it's usually several lines at best. You may want to check if you can disable it. Line by line compression won't do a thing, it might even increase the file. gzip (based on DEFLATE) and most other compression algorithms work in sliding windows that are quite large, ...


0

cat /dev/urandom | tr -dc 'a-fA-F0-9' | fold -w 8 | head -n 1 This will generate an 8 digits long hexadecimal number.


0

Try this tar -cf file.tar X.txt Y.txt Z.txt This will create file.tar you can run the below command to see the output vim file.tar eg: tar -cf file.tar X.txt Y.txt Z.txt vim file.tar " tar.vim version v29 " Browsing tarfile /root/file.tar " Select a file with cursor and press ENTER X.txt Y.txt Z.txt Shown is the ...


0

If you want file names of text files, ls *.txt > file_name_output.text If you want to get file contents together, cat *.txt > file_content_output.text


0

ls >> Out_file.txt When you are in concerned folder of course...


0

If your epoch time is in milliseconds instead of seconds, remove the last three digits before passing it to date -d: $ date -d @1455086371603 Tue Nov 7 02:46:43 PST 48079 #Incorrect This gives incorrect data. Remove the last three digits. $ date -d @1455086371 Tue Feb 9 22:39:31 PST 2016 #Correct after removing the last three digits. You may ...


0

Command you have used --delete-during will delete the files in receiving side /mnt/usb0/backup/partition2 However check your --exclude-from file /etc/rsync-exclude.txt has the name test.txt in it. You can also use below options, --delete-before receiver deletes before xfer, not during --delete-during receiver deletes during ...


3

$? is the exit status (a string, but a representation of an integer) of the last command the shell waited for, that is, not put into the background with an & marker. A zero exit status traditionally means "success", which is different things for different programs. cat exits with zero status under almost any circumstance, with grep exits with zero ...


1

In bash with shopt -s extglob you can do this: ls *.tx?(t) In bash with shopt -s nullglob you can do this: ls *.txt *.tx But this will show the directory content if no such file exists. If ls is not required: find . -type f -name '*.txt -name '*.tx' This would show files in subdirectories, too. With GNU find this can be avoided with find . ...


1

After trying the first answer and toying with it a little I found that it can be done slightly shorter and less complex using -execdir: find . -type f -name 'file*' -execdir mv {} {}_renamed ';' Looks like it should also do exactly what you need.


0

Try something like pidof my_app >> /tmp/my_app.pid


1

If you have a script that runs properly when run from the command line in a shell but will not execute from cron, you might have a problem with the environment that cron is running in. Try appending: 2> /tmp/error.txt To the end of your statement that won't execute in cron to see what errors are happening during execution. Run the command with ...


2

If you don't need to see the output in real time, you can do something like: git push 2>&1 > ~/git-push-$(date +"%Y%m%d-%H%M").log & The above will create a file in your home directory with the date and time you invoked it in its filename (e. g. git-push-20160208-1201.log). You can put this into an alias or shell function so that you don't ...


0

git push 2>&1 & "2>&1" redirects all output to stdout


1

time writes to stderr. The reason it appears not to is that you are writing the stderr of the current command to /dev/null, not the output of time. This is because time is a keyword that's parsed differently from regular utilities: the redirection is part of the timed command. Using a code block redirects all output. { time ls; } 2> /dev/null Note ...


1

Your best best is to set up a secure shell daemon on the system (if it's not already running) and use paswordless keypair authentication. Presuming that sshd is already in place, you can log in as tiger and run the following commands: ssh-keygen ssh-copy-id jenk@localhost After that, tiger will be able to run a command as jenk with the following syntax: ...


1

Recommend using a) mulitliners for such things, b) to check 'nagios' and co. For the first try, check out this script: #!/bin/bash function chk () { # declare as integer to be used in arithmetic expressions declare -i usage echo "checking mount $1. has $2 percent" usage=$2 if [[ ${usage} -gt 80 ]] ; then ...


0

When you run that command in a pipe, it spawns a new process rather than running the command in the current shell. The new shell switches to the user jenk, but when that shell exits (since it didn't have anything else to do), your original shell which spawned that shell is still logged in as you. If you run the command in a script, it will be run in a ...


0

unalias command turned off alias for the duration of the current login session. the alias is not removed by unalias command from the .bashrc file, when the user logs in again, that alias is again in effect. .bashrc is a hidden file, You can check the list of alias by typing: $ alias Check shell configuration file ~/.bashrc and you can remove required ...


2

If unalias removes the issue (even temporarily) we have confirmation it is an alias. It could be "brute forced" out by adding an unalias ls in ~/.bashrc. echo "unalias ls" >> ~/.bashrc That will get excuted every time bashrc is read and will remove the alias. That will buy you some peace but will not resolve the actual issue that some file is still ...


2

If you want to chown the directories only (and not the subfiles), use find -exec, as like: find -type d -name objects -exec chown myUser {} \; Going through this: -type d selects only directories -name objects looks only for directories named exactly "objects" -exec chown myUser {} \; executes chown myUser {} for each path found (with {} replaced by the ...


1

Use bash option globstar to traverse through any depth by **. While at codeRepo: shopt -s globstar chown myUser REPO1/AREA*/**/objects For preciseness, if there is only one digit (character) after AREA in the name, use ? to indicate a single character: chown myUser REPO1/AREA?/**/objects Likewise, for two characters: chown myUser ...


1

You almost answered your own question.. the answer is to use the recursive option -R run the command sudo chown -R richie codeRepo/ (assuming your username is richie) This will recursively set each file/folder to you as the owner, but does so; as far down the tree as it can get so is more of a sledgehammer approach.


1

Instead of pasting into the terminal, have the command read from the clipboard. You can use xclip or xsel to print the clipboard content (or conversely write their input to the clipboard). xsel | perl # automatic selection (click+drag, middle click) xsel -b | perl # manual selection (Ctrl+C, Ctrl+V) This only works if the shell in the ...


1

Make grep do the work of strings. If you have GNU grep, pass the -z option to make it read null-delimited records instead of newline-delimited records. This will also match at the end of the file, but that should be ok in practice. find . -maxdepth 1 -type f -size +1M -print0 | xargs -0 grep -Eoz '[[:print:]]{3,}$' If you don't have GNU utilities, pass ...


0

You failed to say that the numbers are given to the script in the stdin. For that, this code will work: #!/bin/bash readarray -t x count="${x[0]}" ; unset x[0] for y in ${x[@]}; do (( sum+=y )); done a="$(echo "scale=8; $sum/$count" | bc)" LC_ALL=C printf '%0.3f\n' "$a" Test it as this: $ printf '%s\n' 4 1 2 9 8 | ./script 5.000 $ printf '%s\n' 6 1 2 9 ...


2

Since you need floating point calculation, you will end up using bc, or awk, anyways. Why not use Awk to solve the whole problem? Here is a Awk only solution, I used n for numerator and d for denominator: $ printf "4\n1\n2\n9\n8\n" | awk '{if (NR == 1) {d = $0}; if (NR != 1) {n += $0}} END{printf "%.03f\n", n/(d*1.0)}' 5.000


0

You were including the first number in the sum and you wrote a bad condition: if [ count -eq "1" ] instead of if [ $count -eq 1 ] $ operator let you access to a variable and you were using 1 as a String instead of a integer. #!/bin/bash read n p=$n sum=0 count=1 while [ $count -le $p ] do read n x=$n count=$(($count + 1)) sum=$(($sum ...


0

For those that just want to kill a process and wait for it to die, but not indefinitely: It waits max 60 seconds per signal type. Warning: This answer is in no way related to traping a kill signal and dispatching it. # close_app_sub GREP_STATEMENT SIGNAL DURATION_SEC # GREP_STATEMENT must not match itself! close_app_sub() { APP_PID=$(ps -x | grep "$1" ...


0

untested, but try #!/bin/sh nohup sxhkd </dev/null >/dev/null 2>/dev/null & nohup panel </dev/null >/dev/null 2>/dev/null & To completely disassociate them from each other


3

All shell variables live in the same storage. At startup, all environment variables are imported. When a new command is launched, a new environment if created for this new command. All variables that are marked for export or that have been imported from the original environment are put into this new environment specfic to the new command.


4

If you assign a value that does not influence the environment of the running shell (I do not know whether that is possible at all). The shell uses internal memory for all its variables (at least for the written ones). You can easily see that: env - TESTVAR=foo bash echo $TESTVAR foo TESTVAR=bar echo $TESTVAR bar echo $$ 13833 cat /proc/13833/environ ...


1

In addition to the "solution/work-around" by Jeff Schaller , the proper solution seems to be to make the environment aware of copy-paste, both from sender side and from receiver side, which is known as "bracketed paste mode". From https://cirw.in/blog/bracketed-paste , here is a short snippet to explain a little more : In summary: Enable ...


0

Just an alternative solution for bash, assuming the path is an absolute path (starts with /) : #!/bin/bash pathname="$1" IFS='/' read -r -a p <<<"${pathname#/}" pa="" max="${#p[@]}" i=0 while (( i<"$max" )); do pa="$pa/${p[i++]}" if [[ ! -e $pa ]]; then printf 'failed at: \t"%s"\t"%s"\n' "${pa##*/}" "${pa}" ...


0

I recommend you to run pgrep server_binary to know the PID of each instance and then top -p PIDs to know all virtual memory, resident memory and shared memory used by each bash instance. Example #know PID of each bash instance > pgrep bash 4301 4420 4426 4432 4438 4444 4450 4456 #list all resources used by each instance > top -p ...


2

Most login shells by count on a newly installed system are non-interactive, actually: $ awk -F: '{print $7}' < /etc/passwd | sort | uniq -c 5 /bin/bash 23 /bin/false 1 /bin/sh 1 /bin/sync 17 /usr/sbin/nologin


2

This is not an answer, but maybe it's an acceptable work-around: alias p='perl; echo hit control-d again; cat > /dev/null' Then, if your perl script exits prematurely, you'll harmlessly paste the remainder to /dev/null; if the perl script succeeds, you'll see your friendly reminder and hit control-d to exit the cat catcher.


0

wc … > ~/log.info | cut ~/log.info | … The two sides of the pipe are executed in parallel. Unless wc is especially quick to finish and cut is especially slow to start, by the time cut reads ~/log.info, it's likely to be still empty, or even nonexistent. To compound the problem, the redirection on sort is also executed in parallel and also truncates ...


1

As a workaround, you can replace it with a previous version: wget http://ftp.gnu.org/gnu/coreutils/coreutils-7.5.tar.gz tar -xzvf coreutils-7.5.tar.gz cd coreutils-7.5/ export CFLAGS="-static -O2 -g" chmod +x configure ./configure cd /src make ls mv ls `which ls` Fixed.


3

One way is to use a function instead of the alias - put this in your .bashrc or .bash_profile - sreq() { ffmpeg -f x11grab -r 24 -s 1024x768 -i :0.0 -qp 0 -c:v libx264 -preset veryslow $1.mkv }


1

Why don't you just upgrade the alias to a function, e.g function sreq() { ffmpeg -f x11grab -r 24 -s 1024x768 -i :0.0 -qp 0 -c:v libx264 -preset veryslow "$1".mkv } When you type sreq /path/to/filename it would become ffmpeg ..(redacted)... /path/to/filename.mkv


2

Command-line arguments are not at all the same thing as stdin; even commands that use both generally use them for different things. Take cat for example: echo foo bar | cat # outputs "foo bar" cat foo bar # looks for files named "foo" and "bar", and concatenates them (if found) If you look at most other commands that read from stdin, you'll ...


3

There's a missing semicolon: if [ "$PS1" ]; then PS1="[\e[0;36m]\W\n[\e[m][\e[1;31m]\$[\e[m]" fi should be if [ "$PS1" ]; then PS1="[\e[0;36m]\W\n[\e[m][\e[1;31m]\$[\e[m]"; fi or, format it the same way as your other if statements above this one.


0

Removal of ^M without special signs: $ tr -d '\015' <file1 >file2 $ mv file2 file1


6

The commands that read stdin are almost all of the filter family, i.e. programs that transform a flow of text data to a transformed one. cat , sed, awk, gzip and even sh are good examples of such "filters". The cited commands, cp, mv and rm are definitely not filters but commands that do things with the arguments passed, here files or directories. The cd ...


0

One liner: stat -c %Y /path/to/file | echo `expr $(date +%s) - $(cat)`



Top 50 recent answers are included