Tag Info

New answers tagged

4

Two application types come to my mind where shell loops are not considered to be the best approach. The first is data processing; many tools (like sed, awk, perl, etc.) do the loop implicitly and much more performant. The second is (like in your sample code), where some code is executed for a set of files, where find with the -exec switch can also already ...


1

Negative nice values are reserved for system work. If you run a userland program with to high niceness, like -15, some kernel work that it relies on cannot run, so that the program stalls itself. The proper way to make your system usable again is to renice the other CPU hog to higher nice values. renice -n 5 otherpid


1

Running a shell script starts a Bash process as a non-interactive shell. In this mode, history expansion doesn’t actually get carried out. From the Bash manual page, man bash: HISTORY EXPANSION The shell supports a history expansion feature that is similar to the history expansion in csh. This section describes what syntax features are available. ...


0

So, even though echo $PATH echo $PATH gives me the directories in my path, I wanted to know which directory in my path the executable was in. which "executable name" ended up working best for this. What I found at that directory were aliases (OS X) that led to the actual executables. I deleted the aliases, but also made sure to delete the original files as ...


0

#!/bin/bash file="" max=0 for f in /OEBPS/image/*{png,jpg,jpeg} do id=$(identify "$f") size=$(echo ${id} | sed -r 's/.* (JPEG|PNG) ([0-9]+)x([0-9]+) .*/\2*\3/') area=$(($size)) if (( area >= max )) then max=$area file="$f" fi done echo $max $file Don't use ls for iterating over files in scripts - blanks in filenames will brake ...


1

here's a way to get the height and width in one step: IFS=x read w h < <(identify "$file" | grep -oP '\d+x\d+(?=\+)') identify is part of the ImageMagick package. Your "$far" is surely not what you want: for dir in */OEBPS/image/; do for image in "$dir"/*.{jpg,png,jpeg}; do IFS=x read w h < <(identify "$image" | grep -oP ...


0

If I understand correctly, you have directories that contains files called 1, 2, 3, etc. (up to a variable limit) and you want to replace each directory by a file which has the same name as the directory, and is the concatenation of the files in numerical order. In this answer, I'm going to use zsh, because it's a lot easier to use than a combination of ...


5

As @lcd047 told you, aliases are not available to vim. They are also, by the way, not available to shell scripts either, unless you activate the expand_aliases option. Anyway, another choice would be to create a link instead of an alias: sudo ln -s /opt/python3.4/bin/python3 /usr/bin/py That will create a link at /usr/bin/py which points to ...


11

Because the way you define it py is a shell alias, and Vim doesn't know (nor care) about shell aliases. Use an environment variable instead, perhaps like this: $ PY=/opt/python3.4/bin/python3 $ export PY then in Vim: ... exec '!time ' . fnameescape($PY) . ' %' ... Edit: Added fnameescape(). It's needed if $PY contains characters that have a special ...


0

for f in ???.txt do awk -f program.awk "$f" > "output$f" done will process all files whose names are three characters (any characters) followed by .txt.  To restrict it to only files whose names are three digits followed by .txt, use for f in [0-9][0-9][0-9].txt


0

Discussions on this Q&A (This is not an answer, please do not up or down vote) comment #1 by fpmurphy1 Actually, when looking for vulnerabilities in shell code, the first thing to do is look for unquoted variables. It's easy to spot, often a good candidate, generally easy to track back to attacker-controlled data. Humm, I disagree. The first ...


1

Try the following: /usr/bin/sftp -b - USER@remote.server.com <<EOF ... The "-b -" puts sftp in batch mode while still reading from the command line. Batch mode will (on my system) exit sftp and return a non-zero exit code when one of the sftp commands fails.


-1

quick and (very) dirty find . | sed 's/^/"/' | sed 's/$/"/'


3

If your tty has the noflsh flag turned off - you can check with stty -a < /dev/pts/whatever | grep -e -noflsh from another tty, but the default is that it's turned off - then typing the interrupt, quit, or suspend character will flush the input queue. So if you type Ctrl-Z, then fg, it will suspend the currently running command, flush the input, then ...


2

Using echo with the -e switch ( enable the interpretation of backslash escapes): #!/bin/bash function configure_default_vhost() { conf_file="/etc/apache/sites-availabe/000-default.conf" case "$2" in [--production]) # The ">" overwrites; the ">>" appends. { echo -e "<VirtualHost *:80>" ...


7

A few approaches: printf '%s\n' > "$conf_file" \ '<VirtualHost *:80>' \ ' redirect 404 /' \ ' ErrorDocument 404' \ '</VirtualHost>' If you want escape sequences to be expanded replace %s with %b: printf '%b\n' > "$conf_file" \ '<VirtualHost *:80>' \ '\tredirect 404 /' \ '\tErrorDocument 404' \ ...


10

You can use a "here-document" with the - modifier. It can be indented by tab characters. You must switch from echo to cat. cat <<-EOF > /etc/apache/sites-availabe/000-default.conf <VirtualHost *:80> redirect 404 / ErrorDocument 404 </VirtualHost> EOF Or, to keep tabs in the result, you can ...


1

It sounds to me as if the scripts that you are calling should provide the responses that you desire. Here's a way to test for a command and use a specific exit code in those scripts. #!/bin/bash # Test for the existence of a command in the path. command=typo_command if [[ ! $(command -v $command) ]]; then echo "$command does not exist" exit 127 # ...


1

You could perhaps use the script at https://github.com/rcaloras/bash-preexec (as discussed at http://superuser.com/questions/175799/does-bash-have-a-hook-that-is-run-before-executing-a-command) and use the precmd() function to do your $? checking


0

Probably you should send SIGSTOP to bash in order to prevent it from doing anything, and after finishing your task send SIGKILL to bash. Note that SIGSTOP prevents bash from waiting for your task to be finished, and you'll get zombie. After SIGKILL init will reparent your task, and zombie will disappear.


1

I'm not quite sure where that will lead to, but you can do: alias dummy='sh dummy $?' the_program_with_errors dummy and your dummy script would contain: echo $1 An approach without alias is to use a shell function: function dummy { sh dummy $? ;} With that definition you can get the following behaviour (simulated with true, false, and a subshell ...


0

Why not do it even simpler by feeding file1 as search terms to grep and let it search for it in file2? $ grep -f file1 file2 > file3 Please note that on some platforms you need/want egrep or ggrep because of performance issues.


0

The exact answer depends on which terminal emulator you are running, as they have different flags to stop them closing once the command finishes executing. However, you'd want something like this: /usr/bin/xterm -e "sh /home/user/echo.sh" -hold or xfce4-terminal -H -x "/home/user/echo.sh" This executes xterm, telling it to 'execute' the sh .... .sh ...


0

That worked for me find docs/ -type f -iname "*.html" -exec \ perl -i.bak -0pe 's/_uacct = "UA-XXXXXX-X";\nurchinTracker\(\);/test/igs' {} \; Notice that -i.bak makes a copy of the original file with extension .bak, in case anything goes wrong. The replacement is now the string test. Replace that with your long replacement. With your huge replacement it ...


0

You can't escape single quotes inside single quotes. The easiest way for you is to put your script in a file and then run find arts/ -type f -iname "bass.html" -exec sed -i -f your-script.sed '{}' \;


0

Try dos2unix in script file. Sometimes some hidden characters are there in the source. command: dos2unix script_file.sh script_file.sh


1

This can be done easily with awk: awk 'NR==FNR { a[$1] = $2; next; } { if ($1 in a) { print $1, a[$1]; } }' firstFile.txt secondFile.txt this will print matched values and second column from first file. Or you can try this: #!/bin/bash while IFS=' ' read -r -a arr; do while read j; do if [ "${arr[0]}" = "$j" ]; then echo ...


9

The "Network is not reachable" message is printed to stderr, not stdout, so it isn't captured by your substitution ($(ping ...)). You need to redirect stderr to stdout when running ping, not when you log: print_and_log "$(ping -c10 "$i" 2>&1)"


6

If you are only comparing the first line of each file, maybe you care about word-level changes within the line, using dwdiff: dwdiff <(head -n 1 filea) <(head -n 1 fileb) dwdiff has some nice options, like -c to colorize the changed words. Or, using sed instead of head: dwdiff <(sed 1q filea) <(sed 1q fileb) which the manual for head ...


0

You can use: if [ "`head -1 file1`" == "`head -1 file2`" ]; then echo "the same"; fi


17

If your shell supports process substitution, try: diff <(head -n 1 filea) <(head -n 1 fileb)


1

Based on don_crissti answer, I have created a bash script for automating this task. Here is the script: #!/bin/bash if [ -z $1 ]; then echo "usage: screencast <outfile>" exit 1 fi fname=$1 audio=$(pacmd list-sources | sed -n 's/\s*name: <\(.*\.monitor\)>/\1/p') pacmd set-default-source "$audio" echo "Screencast started, to stop it ...


2

dd if=boot1h of="/dev/r$temp1" status=none The status= flag controls which info to suppress outputting to stderr; 'noxfer' suppresses transfer stats, 'none' suppresses all dd (coreutils) 8.21


3

You may use this: num=5; echo $(seq $num) Gives: 1 2 3 4 5 Remark: $(...) syntax is command substitution.


2

A simple loop should be enough: for i in {1..22} do wget "ftp://ftp.ncbi.nih.gov/genomes/Homo_sapiens/CHR_${i}/hs_alt_CHM1_1.1_chr${i}.fa.gz" gunzip "hs_alt_CHM1_1.1_chr${i}.fa.gz" done The loop index doesn't have to be just numbers, you can get the MT, Un, X and Y files as well, with: for i in {1..22} MT Un X Y Since the first set of numbers ...


0

I don't think there are any builtin or bash-completion standard function to complete only bare filenames. Directories can contain files so the standard behaviour for completing a filename is to complete on files and directories (as bash-completion's _filedir does. It has an option for only directories, but not for only files.). You could write a custom ...


0

Instead of scripting the response with expect, just turn off prompting before adding. scp -o "StrictHostKeyChecking no" ... Since you're using expect with ssh in the first place, I'll just say that ssh-copy-id to set up passwordless ssh is a much better way to do things.


1

Why not use --pipe AND --pipepart with GNU Parallel? This eliminates the extra cat and starts direct reads from the file on disk: parallel --pipe --pipepart -a 2011.psv --block 500M ./carga_postgres.sh


1

using find to find all files you want to rename and running an exec script: ` find /main/rel -name file.log -exec mv '{}' '{}.OLD' \; this will run the mv cmd on all found files, the {} (escaped so the shell doesn't do weird things) will be replaced by the filename. this allows you to easily add extra characters to the original filename (e.g. append ...


2

You need to put your aliases in a file that will be read upon start of all sessions. Your ~/.bashrc file should have the following: if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi that means if you have a file ~/.bash_aliases file then it will be sourced and all the aliases defined in it will be applied in the session. It is the best practice ...


1

The common way is to set your aliases in the .bashrc file of your home directory (if you use bash as your shell of course). .bashrc is file read by bash anytime you launch a terminal. Just edit it (watch out, files with a name starting by a . are hidden by default) and add a line like: alias ll='ls -l' If you want to test it without launching a new ...


0

Create a file .bashalias in your home directory, or edit the existing file ~/.bashalias. To have this file read every time you start a bash session, add the following to your ~/.bashrc: source ~/.bashalias


1

Try this: dname=cfp msname=cfp003 log_path="/vol02/logs/${dname}/logs/103602_${msname}/${msname}_start.log" echo "$log_path" Output: /vol02/logs/cfp/logs/103602_cfp003/cfp003_start.log


0

I assume that you want to use awk to process ls -l for the additional information that ls -l provides. In general find and stat gives a more reproducible result, but feel free to use ls. One of the nice things that ls -l does, is it has a fixed width, therefore you can use substr for the start of line, then not specify the length, which will include all ...


1

ORIG=$PS1 PS1="\[${txtund}${green}\]LOCAL\[\[${reset}\]"; PS1+="\$(prompt_git \"\[${white}\] on \[${violet}\]\")"; PS1+="\[${reset}\]"; PS1+="\[ - \u\$: \]"; I have escaped both the colors as well as the final line of text. This solves my issue. It is through using [ ] and escaping colors as well as text, I am able to word wrap my commands in bash ...


2

Since the first argument is a regex, you'll have to both: escape regex special characters, and protect it from the shell ag 'findVersions\(' src/java/com/google


0

No. I don't think there's a single command to do so. you can do renaming these files one-by-one. /main/rel$mv 1.2/somelog 1.2/some_newlog; mv 1.3/somelog 1.3/some_newlog; mv 1.4/somelog 1.4/some_newlog and etc... However, you can write a script to do such job: #!/bin/bash for dir in 1.{2..4} do `mv $dir/some.txt $dir/somenew.txt` done NOTE: Above ...


0

Your gnome-terminal (actually the underlying vte-0.34) emits the wrong sequence for ctrl+Alt+space. The bug (https://bugzilla.gnome.org/show_bug.cgi?id=710349) was fixed in vte-0.36. If you're not afraid of hacking a little bit and you're able to safely revert things in case of trouble, you can try to install vte-0.36 on your Ubuntu 14.04. You'll get many ...


5

You are mixing shell and sqlplus commands. sqlplus doesn't understand redirections, you have to use the spool keyword. For instance: SQL> spool /tmp/result.txt SQL> start requete.sql SQL> spool off From shell: $ sqlplus scott/tiger @requete.sql > /tmp/result.txt


1

I'm not aware of any terminal emulator supporting anything along these lines. The very basic concept of a terminal (or graphical terminal emulator) is to work with a text grid. The screen is divided into a matrix of cells of equal size and each cell contains a letter. You can print a simple text flow, but you can also position the cursor arbitrarily within ...



Top 50 recent answers are included