Tag Info

New answers tagged

0

sed '/[^0-9]/d;s/.$/&p/' <input.txt | sed -nf - file That's two seds working together. The first makes some small attempt at ensuring it only edits appropriate lines by refusing to print any line that contains a single non-numeric character and only editing any lines containing at least one character. Basically its job, though, is just to transform ...


1

POSIXly: case $var in (*[![:blank:]]*) echo '$var contains non blank';; (*) echo '$var contains only blanks or is empty or unset' esac To differentiate between blank, non-blank, empty, unset: case ${var+x$var} in (x) echo empty;; ("") echo unset;; (x*[![:blank:]]*) echo non-blank;; (*) echo blank esac


1

When you write: alias thm="cd $SET_DIR/sites/all/themes/" you're expanding the value of SET_DIR at the time you define the alias. That means you get the same value every time you run the alias, even if you've changed the variable value in between. If you backslash-escape the $ then the variable will be dereferenced when you use the alias instead: $ ...


2

Even more concise #!/bin/bash servers=( "1.1.1.1" "2.2.2.2" "3.3.3.3" "4.4.4.4" "5.5.5.5" "6.6.6.6" "7.7.7.7" ) for i in "${servers[@]}"; do ping -c 1 $i > /dev/null && /usr/bin/snmptrap -v 2c -c public ... done NOTES: The "&&" after ping means "IF TRUE THEN", and in the case of ping, TRUE means ping did not fail (i.e. the server ...


0

In the purest form, you can use pkill server1 That assumes server1 is actually the process name, not just somewhere in the command line - otherwise add an -f. pkill -f server1CommandArgument But wait! You can test what pkill will match and kill with the command pgrep - which is technically almost the same. The difference it: instead of killing, it ...


0

If this is an assignment, look at the other answers. If you just want to get the task done, use the calendar command, which is included in most Unix systems. On Linux: $ mkdir ~/.calendar $ echo -e "Jul 30\tMother's Birthday" >> ~/.calendar/calendar $ echo -e "08/02\tPrasant's Birthday" >> ~/.calendar/calendar $ echo -e "Aug 15\tPrabhat's ...


1

As requested, below is a working bash script. I use "=" sign field delimiter within each user 'record', and a space is the record delimiter. Note, I added fictitious emails for completeness. #!/bin/bash # DATE=$(date '+%m-%d-%Y') bdays='08-02-2014=Prashant=abc@example.com 08-15-2014=prabhat=123@example.com 09-16-2014=Aks=xyz@example.com ...


1

You have to indicate what to kill: kill -9 $(ps | grep "server1" | grep -v grep | awk '{ print $1 }') You can also use the trick: kill -9 $(ps | grep "server[1]" | awk '{ print $1 }')


2

I've made some comments in line to explain what different parts of the script are doing. I've then made a concise version of the script below. #!/bin/bash servers=( "1.1.1.1" "2.2.2.2" "3.3.3.3" "4.4.4.4" "5.5.5.5" "6.6.6.6" "7.7.7.7" ) # As is, this bit doesn't do anything. It just pings each server one time # but doesn't save the output for i in ...


0

Here's the answer in dodgy pseudocode. You can implement in any language you like. With a file of consistent formatted dates (called 'birthdays'). today=GET_TODAYS_DATE() While not end of file birthdays do read from file DATE NAME if today=DATE then mail address with "Today is NAME's birthday" endif endwhile Run it every day in cron at 1 ...


1

I have extended your script, so that you can run it once on startup and it will do it's job between 9PM and 9AM. #!/bin/bash -· LOGFILE="/tmp/autotest_run_count.txt" trap "echo manual abort; exit 1" 1 2 3 15 RUNS=0 while [ 1 ] ; do· HOUR="$(date +'%H')" if [ $HOUR -ge 21 -a $HOUR -lt 9 ] ; then # run program libreoffice || exit 1 ...


-1

For testing if variable is empty or contain spaces, you can also use this code: ${name:?variable is empty}


2

Depending on what you want exactly to do, and the structure of your files, other possibilites may be available, such as : ls -1tq /dir/*/readme.txt | head -n 1 Returns the full name of the most recent readme.txt found in any subdirectory (not recursive) of /dir/ The usage of * as part of the path (not just as part of a filename) often being underknown, I ...


1

For more portability, you can use perl: $ perl -MList::Util=reduce -le ' BEGIN { $dir = "." } opendir DIR,$dir; print shift @{(reduce {$a->[1] > $b->[1] ? $a : $b} map {[$_,(stat($_))[9]]} grep { -d and !/^..?$/ } readdir DIR)} ' .Skype Change $dir to whatever directory you want ...


3

You don't need any elaborate pipelines for this. Moreover, you don't need to find anything - you already know where each file is, you just don't know which of them is newest. This is easily handled. To demo, here's my little test: mkdir ./dir1 ./dir2 ./dir3 for d in 1 2 3 do touch ./dir$d/samefile sleep 1 done That creates the test set. Now, which ...


0

Short answer: look into man find and the 'time' options. This will locate the file(s), then use the -printf option to display the path of the file(s), which then can be used for cd <path> One way to use find and extract DIR of the last accessed file (within the last 24h) in current dir and its sub directories lastAccDir="$(find 2>/dev/null . -type ...


0

Shell syntax You seem to be confused regarding conditionals in shell scripts. Every shell command has an exit status, which is an integer between 0 and 255, with 0 meaning success and any other value meaning failure. Statements like if and while that expect boolean operands inspect the exit status of the command and treat 0 (success) as true and any other ...


2

The easy way to check that a string only contains characters in an authorized set is to test for the presence of unauthorized characters. Thus, instead of testing whether the string only contains spaces, test whether the string contains some character other than space. In bash, ksh or zsh: if [[ $param = *[!\ ]* ]]; then echo "\$param contains characters ...


3

See the Wooledge wiki on tests and conditionals: -w FILE: True if the file is writable by you. So, you could test it with: [[ -w "$file" ]] If you aren't using bash, you could equally use [ -w "$file" ]


14

Most commands that accept --foo as an option also accept -- by itself as an "end of options, start of arguments" marker - so you could do: printf -- "--no-color\n--format-doc\n--no-profile\n" >> ~/.rspec-test But the more specific answer to your exact example is that the first argument to printf is a format specifier, and you're making things more ...


4

If you're using GNU mv you have the following option. $ mv -b source/* dest/. This switch tells mv to push any files that collide in the dest/. directory to a backed up version, typically adding a tilde (~) to the end of the file, prior to moving files into the directory. Example Say I have the following sample directories with files. $ mkdir source ...


0

Here is the script. If you call it move, you will have to use the command move file destination #!/bin/bash FILE=$1 DEST=$2 if `ls ${DEST}/${FILE} > /dev/null` then base=`echo ${FILE} | sed 's/\(.*\)\..*/\1/'` ext=`echo ${FILE} | sed 's/.*\.\(.*\)/\1'` r=$RANDOM mv ${FILE} ${DEST}/${base}-${r}.${ext} else mv ${FILE} ${DEST} fi ...


0

May consider mv with the interactive option -i.


1

In order to determine if a variable is empty you first determine if it is set. An unset variable and an empty variable are not one and the same. This can be especially useful information before trying to set a variable that has been set as empty (sometimes used to represent a condition is true for environment variables) and readonly. If you attempt to do ...


0

Apparently the script on OP is a bash script. At least there's a basic error: the bracket enclosing ifconfig | grep ... commands shall be removed, so exit status of grep can be treated as a true/false condition for while loop.


0

Ping will return a 0 response if at least one attempt was successful. You might consider pinging the server you are connecting to until it is successful.


1

Just count the output of ip add show For example: root@xxxxxxlp01 ~ $ ip add sh dev eth3 | grep inet root@xxxxxxlp01 ~ $ ip add sh dev eth1 | grep inet root@xxxxxxlp01 ~ $ ip add sh dev eth0 | grep inet inet xxx.xxx.64.91/24 brd xxx.xxx.95.255 scope global eth0 inet6 fe80::224:e8ff:fe78:4dfb/64 scope link root@xxxxxxlp01 ~ $ ip add sh dev eth0 | ...


1

The only remaining reason to write a shell script, instead of a script in a good scripting language, is if extreme portability is an overriding concern. The legacy /bin/sh is the only thing you can be certain you have, but Perl for instance is more likely to be available cross-platform than Bash. Therefore, never write shell scripts that use features that ...


13

First, note that the -z test is explicitly for: the length of string is zero That is, a string containing only spaces should not be true under -z, because it has a non-zero length. What you want is to remove the spaces from the variable using the pattern replacement parameter expansion: [[ -z "${param// }" ] This expands the param variable and ...


0

Change the sql statement to contain table name as well sqlplus /@ < output.dat SET PAGES 0 select 'Emp,' || Count(*) from Emp where date= current_date-1; EXIT; ! awk -F "," '{a[++n] = $1; b[n] = $2; next} END {printf "Table Name"; for(i=1; i<=n; i++) printf ",%s", a[i]; print""; printf "Result Set"; for(i=1; i<=n; i++) printf ",%s", b[i]; print ...


1

Try this example awk 'BEGIN{ OFS="|"; print "Column1|Column2|Column3|Column4|Column5|Column6"}; NR > 1{print "IND", "INR", $6, $7, $8, $9;}' Inputdata.txt > Output.xls


0

As others have said, local will always return 0. The solution is to declare the variable first: function testcase() { local MYRESULT MYRESULT=$(false) if (( $? != 0 )); then echo "False returned false!" return 1 fi return 0 } Output: $ testcase False returned false! $


0

I don't think that the Dialog program has an option to validate the content of fields. Have your program run dialog in a loop, throwing the user back into the dialog box if they enter incorrect values such as empty fields. #!/bin/bash shell= groups= user= home= error_message= IFS=$'\n'; set -f while [[ -z $shell || -z $groups || -z $user || -z $home ]]; do ...


0

Maybe it can get shorter exts=( *.jpg *.png *.gif ); printf "There are ${#exts[@]}" extensions;


4

I'd suggest a different approach, avoiding the possible word-splitting issues of ls #!/bin/bash shopt -s nullglob for ext in jpg png gif; do files=( *."$ext" ) printf 'number of %s files: %d\n' "$ext" "${#files[@]}" # now we can loop over all the files having the current extension for f in "${files[@]}"; do # anything else you like with ...


2

My approach would be: List all files in the directory Extract their extension Sort the result Count the occurrences of each extension Sort of like this: ls | awk -F . '{print $NF}' | sort | uniq -c | awk '{print $2,$1}'


1

awk 'NR==FNR{linesToPrint[$0];next} FNR in linesToPrint' line-numbers.txt file.txt


5

Shell scripts are normally treated as if they were the same as any other kind of executable file, such as binaries, Python scripts, Perl scripts, or any other kind of script. They have a shebang at the top that directs the kernel to execute them through the shell. They are expected to be invoked the same way as any other command. As such, a new shell is ...


2

dialog is a great tool for what you are trying to achieve. Here's the example of a simple 3-choices menu: dialog --menu "Choose one:" 10 30 3 \ 1 Red \ 2 Green \ 3 Blue The syntax is the following: dialog --menu <text> <height> <width> <menu-height> [<tag><item>] The selection will be sent to stderr. ...


0

To formalise and expand on what someone said in a comment, when you put something in root's crontab it will run inside /root, not in the directory the script is in, because cron doesn't even know where that is. Because your backup files aren't in that directory tree, the find command never reaches them. So the job is running, it just never finds any files to ...


1

for f in file* ; do { read line read na num na } <"$f" printf '%s\t%s\n' "$f" "$num" done | sort -t\<tab> -n -k2,2 Though it's hard to tell for sure because you don't note the field separator, the above assumes awk defaults but does the job with native shell script, I think.


3

Try: $ awk 'FNR == 2' file1 file2 filen | sort -n -k2,2 With gawk, you can use nextfile for efficience: $ gawk 'FNR == 2 {print FILENAME,$2; nextfile}' file1 file2 filen | sort -n -k2,2 or you can write your own nextfile function in other awk implementation refer to this. If you don't have gawk, you can use perl for more portable: $ perl -anle 'print ...


0

Normally, when you run a command asynchronously (i.e., run it in the background with &) in a non-interactive shell (e.g., a shell script), and you don’t explicitly redirect the command’s standard input, the shell redirects it to /dev/null, so it doesn’t interfere with the foreground.  Of course your problem is that you want the background process to ...


3

If understand what you're wanting, using read should accomplish your goal. However you don't want the read to sit there blocking indefinitely, so you pass a timeout. For example: #!/bin/bash sleep 5 echo done sleeping read -N 10000000 -t 0.01 You can type whatever you want while sleep is running. Once it finishes, bash will invoke the read which will ...


1

I did this two ways, though I think I like this best: : $(( afterl=( lastl=$(wc -l <~/file) ) - 2 - $(( beforel=( matchl=$(sed -n "/$IP/{=;q;}" <~/file) ) - 1 )) )) for n in last match afters befores do printf '%s line%s :\t%d\n' \ "${n%s}" "${n##*[!s]}" $((${n%s}l)) done That saves all of those as current shell variables - and evaluates ...


1

If you can install the rlwrap utility, then it is as simple as doing rlwrap ./yourscript.sh This will allow you to use the up and down array keys to browse through history, as well as the right and left arrow keys for editing the current command, for programs that do not support it already.


1

An awk solution reporting number of lines before and after last match awk '/192\.168\.1\.1/{x=NR};{y=NR} END{printf "before-%d, after-%d\n" , x-1, y-x}' file


1

I was trying the following commands, which are a bit complicated, but would give accurate results: After: a=$(cat file | wc -l) && b=$(cat -n file | grep <Pattern> | awk '{print $1}') && echo "$a - $b" | bc -l Before: echo "`cat -n file | grep <Pattern> | awk '{print $1}'`-1" | bc -l


2

Maybe the easiest is, sed -n '/pattern/{=; q;}' file Thanks @JoshepR for pointing the error


4

Nunber of lines before and after a match, including the match (i.e. you need to subtract 1 from the result if you want to exclude the match): sed -n '0,/pattern/p' file | wc -l sed -n '/pattern/,$p' file | wc -l But this has nothing to do with IP addresses in particular.



Top 50 recent answers are included