Tag Info

New answers tagged

0

You don't have a shebang line at the top, so the shell you are using (sh, dash) is likely not to support [[. You should start the script with: #!/bin/bash or any other location bash is in, in the unlikely case that is not the path to bash on your system (type bash).


0

This is script i am running : for d in $(find /backup/ASHISH -maxdepth 1 -type d) do ls -l |awk '{ print $9 }' |grep CC*_date +"%m%d20%Y"|xargs echo echo $d done >test.out This script is giving me output as /backup/ASHISH/D /backup/ASHISH/E /backup/ASHISH/R /backup/ASHISH/CL /backup/ASHISH/E /backup/ASHISH/C I expect shell script to return all the ...


0

If you strip out the unwanted chit-chat, your question boils down to the uninformative: "How do I use sed to display output in a new text file?" So you do man sed to read the manual pages and read through the options. Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from ...


1

Use a for loop: for d in $(find /path/to/dir -maxdepth 1 -type d) do #Do something, the directory is accessible with $d: echo $d done >output_file It searches only the subdirectories of the directory /path/to/dir. Note that the simple example above will fail if the directory names contain whitespace or special characters. A safer approach is: find ...


1

I am a complete bash newbie, but a UN*X veteran. Although doubtless this can be done in Bash shell scripting, in the old days we used find [-maxdepth <levels>] <start-dir> -exec <command> ; to achieve this. You could do a man find and play around, perhaps until someone tells you how to do it in bash!


0

You can put relative paths in the search path. It's dangerous, because it could cause you to execute unexpected binaries when you're in a directory which isn't part of your project; don't do it on a multi-user machine. PATH=…;node_modules/.bin/ionic;… For more safety and flexibility, you can change the search path each time the current directory changes. ...


1

Bash makes it relatively easy to apply a transformation like stripping prefixes and suffixes to elements of an array. shopt -s nullglob # if there are no matches, produce an empty list versions=(hsli*.h5) # list matches versions=("${versions[@]#hsli}") # strip prefix versions=("${versions[@]%.h5}") # strip suffix printf ...


2

First, your snippet executes the command echo {} : ;if [ -f {} ]; then echo file; else echo directory;fi because it needs its output to evaluate the command substitution. Since there is no file named {}, this produces the output {} : directory Then the find command is executed with the arguments -exec, echo, {}, :, directory, so for every file, it ...


0

This is how I used it: f() { ls $AAA return $? } g() { f return $? } d() { g echo $? } AAA= d _ <contents of dir> 0 _ AAA=sdsasdasd d _ ls: sdsasdasd: No such file or directory 2


2

Without ls, since you're just populating its list with shell globs anyway, you can cut out the middle-man like: glob_hsli()(IFS=.;set +f set -f -- '' hsli*.*.h5 for h5 do case ${h5#*.} in (*[!0-9]*.*|.*|'') : ;; (*) set $h5 "${1:-0}"; shift $((3>>($2>$4)));; esac;done printf "0.%d\n" "${1:?No Match Found!}" ...


0

You cannot put a space after filename= Remove the space and you will be good.


1

Why first assign the timestamp to value? You can just do: filename="/home/pi/media/"$(timestamp)".h264" And you should quote the filename in the recording command (in case there are spaces in the path, etc.): #Recording raspivid -w 800 -h 600 -t 15000 -o "$filename" -n -rot 270


0

I don't know if it acceptable, but you can remove everything before the second pipe |, and everything after the first space minus 2 characters : sed -e 's/^[^|]*|/>/' -e 's/^[^|]*|/>/' -e 's/.. .*$//'


0

As you said, it doesn't like using the :index and the /pattern/ modifiers in the same expression: ./t.sh: line 19: FUNCNAME[*]: 1/isCircularRef_test/: division by 0 (error token is "/")


2

You could try to remove the call to greeter from your .bashrc, and put it in ~/.bash_profile. It's only called with login shell.


1

Don't use function port() - it doesn't actually make any sense. When declaring a bash or ksh function with the function command you don't use the () but the shell accepts it as a forgivable syntax oops and acts like you didn't use function at all. So don't. port() case ${1:--} in (B) OPT_B=8000;; (*[!0-9]*) ! printf 'chosen value %s not in %s\n' ...


0

Given the simplicity of your while loop, it makes more sense to use xargs for your task. It should also be faster, though I doubt your test/ directory would be large enough to notice. find test/ -type f -print0 |xargs -0 cp -ipt app/ Note that -t is a GNU extension. If that is problematic, you'd need something like this (to do this with GNU xargs, ...


2

I'm pretty sure you just want sudo's little-k option, sudo -k vim ~/thefile which is documented to completely ignore your cachefile: When used in conjunction with a command or an option that may require a password, this option will cause sudo to ignore the user's cached credentials. As a result, sudo will prompt for a password (if one ...


0

As a first cut at it, strace -e execve -b execve -f -qqv -e signal='!all' bash for non-smoketest use you'd have to redirect stderr to some logger pipe, or litter some poor directory somewhere with files using strace's -o, maybe -o ~/commandtraces/$(date +%Y%m%d%H%M%S).$$ To do it for all interactive shells I'm thinking you'd need a guard variable in ...


2

There isn't an option to sudo that will do exactly what you want, but you can make a shell function that will create a new command sudok, which will run the sudo command and then have sudo remove its cached credentials. function sudok () { sudo "$@"; sudo -K; } Add that line to your ~/.bashrc or ~/.bash_profile to make it permanent.


0

echo eats the newlines when you do not use quotes. You already found the improvement echo "$VAR_1" Now do the same for the here-document: echo "`cat <<EOF $VAR_1 EOF`"


0

When it is your local system, and you are very carefully, you can replace all /usr/bin files by wrappers. Something like cp -pr /usr/bin /usr/orgbin cd /usr/bin for f in *; do echo "/usr/orgbin/echo $f used >> /tmp/bin_usage.out" > $f chmod +x $f done First try with 2 innocent programs?


1

You can define a library of predefined math functions for bc and then use them in the command line. For example, include the following in a text file such as ~/MyExtensions.bc: define max(a,b){ if(a>b) { return(a) }else{ return(b) } } Now you can call bc by: > echo 'max(60,54)' | bc ~/MyExtensions.bc 60 FYI, there are free math ...


0

So, I might have made an error in not posting enough details about the child script - I simplified it for the purpose of this question, but maybe too much. The exit statement was buried inside a code block (between { and }) which was piped to tee for logging: { #... if [ $SOME_BAD_CONDITION ] ; then exit 1 fi #... } | tee -a $LOGFILE echo ...


1

Since your child processes exit with a proper zero/non-zero exit code convention, and given that you execute them sequentially, I'd say you could just use the && operator: #!/bin/bash ./child_1.sh [[ $? -ne 0 ]] && exit # Exit if non-zero exit code ./child_2.sh ./child_3.sh ./child_4.sh exit 0 Here, [[ $? -ne 0 ]] && exit acts ...


0

Looks like your issue stems from how you throw the error in your child script. From man set "if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in a if statement, part of an && or || ...


0

See man sudoers; a timestamp_timeout setting is described there. Set it to 0 to make sudo always prompt for a password.


1

If you use some text editor try to use just one: awk -F ".scheduleName." ' NR==1{printf "%s ", FILENAME} NR<4{printf "%s ",$2} END{print""}' $(ls -t | head -1) I hope is there more than 1 scheduleName in line to remove first and last symbols from second field?


3

The <(...) statement in bash is process substitution. The process in <(...) is run with its input or output connected to a FIFO or some file in /dev/fd. See it with: echo <(echo foo) It prints something like /dev/fd/63. That is the file descritor. The <(...) part is then replaced with that file descriptor. So in your statement the call would ...


4

compare file modification times with test, using -nt (newer than) and -ot (older than) operators: if [ "$file1" -ot "$file2" ]; then #do whatever you want; fi


4

I haven't tried it, but find should be able to handle the whole operation just fine: $ find dir/ -type f ! -newer reference -delete ... or... $ find dir/ -type f ! -newer reference ! -name reference -delete Basically: ! -newer reference matches files which have been modified less recently than reference. -delete deletes them. ! -name reference ...


0

Through python3 #!/usr/bin/python3 import csv import sys file1, file2 = sys.argv[1], sys.argv[2] with open(file2) as second, open(file1) as first: second_list = second.readlines() first_list = first.readlines() for line1 in first_list: for line2 in second_list: if line1.split(':')[1] == line2.split(':')[1]: ...


2

Maybe by storing the output in variables and writing these variables to the file? output1=`ls -tr | tail -n1` output2=`head -n3 bla-1357135486.xml | awk -F 'scheduleName' '{ print $2 }' | sed -r 's/^.{1}//' | sed -r 's/.{1}$//'` echo "$output1 $output2" > /tmp/output.file


0

let me try point something basic . 1. if we already can travel through directory trees , next thing is to search in the current visiting directory . this depends on what style of pattern syntax we want to support . regex is a whole different thing . maybe we are satisfied with the shell built-in pattern grammar . then this will do . for i in * ; do for p ...


0

Most people would just do sort -n input | head -n1 (or tail), it's good enough for most scripting situations. However, this is a bit clumsy if you have numbers in a line instead of a column - you have to print it out in a proper format (tr ' ' '\n' or something similar). Shells are not exactly ideal for numerical processing, but you can easily just pipe ...


-1

it's define Linux copy range of folders:- $ shopt -s extglob # to enable extglob $ cp !(b*) new_dir/


2

With sed you can probably do: sed 's|[^:]*:\([^:]*\).*|/^[^:]*:\1:/s/$/:&/;t|' file2 | sed -f - file1 ...which would involve one sed process reading the second file and writing a sed script for editing the first into a second sed's stdin. As near as I can tell you shouldn't have any problem with directly injecting the contents verbatim into a regexp ...


7

This sounds like a task for join: join -t":" -o "1.1,1.2,1.3,1.4,1.5,2.1,2.2,2.3" \ -j 2 <(sort -k2,2 -t: test1) <(sort -k2,2 -t: test2) Output: Julian:Brude:Other:Other:Other:Jb:Brude:kemin Robert:Dillain:Other:Other:Other:R:Dillain:bodent Megan:Flikk:Other:Other:Other:Mb:Flikk:kentin Jesus:Kimmel:Other:Other:Other:Jbb:Kimmel:verlin ...


4

This is simple task for awk: awk -F':' -vOFS=':' 'NR==FNR{a[$2]=$0;next}{print $0,a[$2]}' file2 file1 First we set : as field separator both for input (with -F) and output (with OFS) then if first file is processed (file2) we assign whole line to table element indexed with second field. When next next file (file1) is processed we print its lines adding ...


2

Just include an actual newline inside the quotes (this works with either single or double quotes). Note that if the second line is indented, the spaces are part of the string. Furthermore always use double quotes around variable substitutions. str="deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free deb-src http://ftp.cn.debian.org/debian/ ...


13

If you know you are dealing with two integers a and b, then this simple shell arithmetic expansion using the ternary operator is sufficient to give the numerical max of them: $(( a > b ? a : b )) E.g. $ a=10 $ b=20 $ max=$(( a > b ? a : b )) $ echo $max 20 $ a=30 $ max=$(( a > b ? a : b )) $ echo $max 30 $


6

You can compare just two numbers with dc like: dc -e "[$1]sM $2d $1<Mp" ... where "$1" is your max value and "$2" is the number you would print if it is lesser than "$1". That also requires GNU dc - but you can do the same thing portably like: dc <<MAX [$1]sM $2d $1<Mp MAX In both of the above cases you can set the precision to ...


0

Inside awk you don't have direct access to shell variables, you need to pass them as an options, so change awk command to something like: awk -v SF="$SCALINGFACTOR" '{printf($1"\t"$2"\t"$3"\t"$4*SF)}'


3

Two brace expansions do work, they just don't work the way you want them to: $ touch abc $ mv {a,}b{c,d} mv: target `bd' is not a directory $ echo mv {a,}b{c,d} mv abc abd bc bd They are expanded separately - effectively the first one is expanded, leaving you with mv ab{c,d} b{c,d} and then the second is expanded, leaving you with mv abc abd bc bd.


3

Too long for a comment: While you can do these things e.g. with the sort | head or sort | tail combos, it seems rather suboptimal both resource- and error-handling-wise. As far as execution is concerned, the combo means spawning 2 processes just to check two lines. That seems to be a bit of an overkill. The more serious problem is, that in most cases you ...


3

You can define a function as function maxnum { if [ $2 -gt $1 ] then echo $2 else echo $1 fi } Call it as maxnum 54 42 and it echoes 54. You can add validation info inside the function (such as two arguments or numbers as arguments) if you like.


10

sort and head can do this: numbers=(1 4 3 5 7 1 10 21 8) printf "%d\n" "${numbers[@]}" | sort -rn | head -1 # => 21


0

If you want to work with an arrayed expansion result in a basic POSIX shell you have to take care with both $IFS and filename generation. You can work safely with unquoted variables - but it is usually not the most simple way to do it. Shell's are designed to work first and foremost with arguments - so I suggest you use the argument array: set -- ...



Top 50 recent answers are included