New answers tagged

0

Try this one: ssh -t user@sshserver.com ' touch /tmp/servicestatus.txt ; service lfd status > /tmp/servicestatus.txt ; mutt -s "Service Status" email@address.com < /tmp/servicestatus.txt ' As of: -t to open the pseudo-terminal touch command to create the file, once Ssh's pseudo-terminal seems to do not create it. Notice that """ differs from "`". ...


-1

service lfd status >output cat output|mail -s "subject" emailid </dev/null


3

Your problem is that old is never set, at least, not in the part of your code that you have posted. grep will always match when searching for a null string "", and return a zero exit code: $ echo $PWD | grep ""; echo $? /home/jim 0


1

It would be more efficient to use a string comparison in bash: if [[ $PWD != *$old* ]]; then assuming $old has some value (it's not set in your function, which is your issue). I think a partial implementation of your function could look like cd () { if [[ $PWD != *$1* ]]; then printf 'cd: string not in pwd: %s\n' "$1" return 1 fi ...


0

I have done by using if condition and awk count_line=`awk '{print NR}' p.txt| sed -n '$p'` for ((i=1;i<=$count_line;i++)); do j=`awk -v i="$i" -F "" 'NR==i{print NF}' p.txt`; if [[ $j == "1" ]]; then awk -v i="$i" -F "" 'NR==i{print "000"$0}' p.txt; elif [[ $j == "2" ]]; then awk -v i="$i" -F "" 'NR==i{print "00"$0}' p.txt ; elif [[ $j == "3" ]]; then ...


0

cat file.txt | awk -vlen=4 '{ add="" #empty prefix to be added if(length($1)!=len){ for(i=(len-length($1));i<=length($1);i++) add=add"0" #add prefix as necessary } print $1""add }' Feel free to change the variable len to your liking.


0

What about find?, the easiest way I can think is using it, maybe it's a little rough but it must do the job find /var/opt/ -type f -name "*.log" -exec grep -iH 'err\|warn\|fail\|whatever' {} >> total.log \; It's not clear for me if you just want to filter all log files (from all the days) or just from today, if you need to filter with date you can ...


-1

you can use regex for ip check something like this \b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b https://www.regular-expressions.info/ip.html


1

We can use ipcalc to validate an IP addesss From man: ipcalc - perform simple manipulation of IP addresses example ipcalc -cs 192.168.1.1/30 && echo OK || echo NOT_OK or ipcalc -cs "$a.$b.$c.$d/$x" && echo OK || echo NOT_OK or ipcalc -cs "$ip" && echo OK || echo NOT_OK


0

You could zero-pad your output with printf: $ printf '%08d\n' $(echo "obase=2; 10" | bc) 00001010


0

Well you can use: #!/bin/bash y=00001010 A=3 y=${y:0:-$A} y_zero=$y y_one=$y for((i=0;i<$A;i++)) do y_zero=$y_zero"0" y_one=$y_one"1" done echo $y_zero $y_one Output will be 00001000 00001111


1

$ grep -x -f <(sed 's/\./\\./g;s/^/.*/' listB) <(grep -v -F -x -f listB listA) .best.co .test.server.cloud.us-east.amazonaws.com .abc.com.co .def.museum.hiroshima.jp .xyz.xxx.yyy.net Explanation as two commands: 1.) grep -v -F -x -f listB listA Remove literal duplicates from listA and use this output as input of the second grep. This leaves these ...


0

# save valid extension from listB vexts=($(sed "s/^.*\.//g" listB)) # loop over listA and filter desired output while read line; do if [[ " ${vexts[@]} " == *" ${line##*.} "* ]] ; then echo "${line}"; fi done < listA


0

It seems there are two issues here. First, defining a function requires the function keyword, at least on my system, thus the function definition should be: function certspotter(){ curl -s https://certspotter.com/api/v0/certs\?domain\=$1 | jq '.[].dns_names[]' | sed 's/\"//g' | sed 's/\*\.//g' | sort -u | grep $1 } Then, as mentioned in the comments, ...


1

I think you want to have cpu Usage string to be shown on the same line each time and to be followed by the cpu Idle line immediately. To achieve that you can use tput and el (clr_eol) terminal capability to remove line and cuu (parm_up_cursor) to move n lines up. You can read about terminal capabilities in man terminfo. Your script would look like this: #!/...


0

Your scripts exits and bluetoothctl is terminated as soon as the echo is done, which means that bluetoothctl may not have enough time to do its thing. It is likely that the co-process exits due to receiving a PIPE signal when trying to write something to standard output (which is closed by the script exiting). You have two options here (quite possibly more):...


3

You don't have copy them one by one, you can paste all the lines together and newlines will work as Enter. The reason that ( var1="myvar1" var2="myvar2" ) doesn't work is that because it's executed in a subshell. It would work if you printed contents of the variable before the final ): ( var1="myvar1" var2="myvar2" echo $var2 ) It's explained in ...


0

The parenthesis you used causes the enclosed commands to be executed by a subshell; hence once that shell exits, de variables are still not set in the current shell. I'm at a loss why you think those parenthesis would set those variables "in one go", or why it would be necessary to them them "in one go"; however you could place those assignments on one line ...


1

Your variable (files_to_scp) is holding the literal string "{aaa,bbb}*_list.txt", NOT an expansion of all matching files. bash doesn't expand braces on scalar variable assignments. bash does, however, expand them for arrays. Use an array instead. e.g. files_to_scp=( {aaa,bbb}*_list.txt ) scp "${files_to_scp[@]}" user@host:. Here's a (simplified, ...


3

The brace expansion syntax {aaa,bbb} must have the braces and the , character to be unquoted for it to expand to a valid/possible set of files. In the OP, the "{aaa,bbb}*_list.txt" is kept intact as a literal string and not expanded at all. Also storing a brace expansion in a variable and interpolating that variable to expand the brace will never work ...


0

for dir in */ do (cd $dir && echo "$dir [$(git rev-parse --abbrev-ref HEAD)]") done It will output (almost) what you want. project1/ [master] project2/ [dev] project3/ [master] project4/ [master]


0

This is just a simple concatenation of a line with fixed text (X Y Z) and part of a single line from one file (SummaryX.txt) and the entire contents of another file with a related filename (recordX.txt) #!/bin/sh for sfile in Summary*.txt; do rfile="$(echo "$sfile" | sed -e 's/^Summary/record/')" ofile="$rfile.new" { echo X Y Z sed -E -n -e ...


5

Save your crontab to a file: crontab -l > my-crontab Delete your crontab: crontab -r Then load back the crontab from the file: crontab my-crontab


0

If I undersand you correctly, this is my proposal: for i in record*.txt; do xyz=$(grep -oP "(?<=RESULT ).*(?=\*\*\*)" $i) sed -i "1 iX Y Z\n$xyz\n" summary${i//record/} done Loop through the files named record*.txt for i in record*.txt; do Capture the string between RESULT and *** xyz=$(grep -oP "(?<=RESULT ).*(?=\*\*\*)" $i) Add X Y Z in the ...


0

Simple method (where the number of fields AND their names are known): $ awk -F' *: *' -v OFS='\t' ' BEGIN {print "NAME","AGE","PLACE"; IGNORECASE=1}; $1 == "Name" {name=$2}; $1 == "Age" {age=$2}; $1 == "Place" {print name, age, $2}' input.txt NAME AGE PLACE AAA 22 XX BBB 33 YY This requires only one pass through ...


-2

Done by below command and it worked fine awk '{print $NF}' i.txt > finalfile z=`cat finalfile| awk '{print NR}'| sed -n '$p'` for ((i=1;i<=$z;i++)); do j=$(($i+2)); sed -n ''$i','$j'p' finalfile| sed "N;s/\n/ /g"| sed "N;s/\n/ /g";i=$(($i+2)); done| awk 'BEGIN{print "NAME AGE PLACE"}{print $0}' output NAME AGE PLACE AAA 22 XX BBB 33 YY


1

It's as simple as this: true && echo ok || echo fail false && echo ok || echo fail A typical command may return null (as true does) or may return not null (as false does) depending on whether the operation succeeded or failed. ./main_script.sh && ./report_success.sh || ./report_failure.sh If you had to run several commands for ...


2

Assuming your main_script.sh is fairly standard and passes a 0 for a successful run and 1 for an unsuccessful run, you can probe the status via $? like so: ./main_script.sh if [ $? -eq 0 ]; then ./report_success.sh else ./report_failure.sh fi


4

if main_script.sh; then report_success.sh else report_failure.sh fi This uses the exit status of main_script.sh to determine whether it was successful (exit status 0) or not (exit status non-zero) and then runs the appropriate report script.


0

The pseudo-code in the question does not corresponds to the title of the question. If anybody needs to actually know how to run command 2 if command 1 fails, this is a simple explanation: cmd1 || cmd2: This will run cmd1, and in case of failure it will run cmd2 cmd1 && cmd2: This will run cmd1, and in case of success it will run cmd2 cmd1 ; cmd2: ...


8

You could use the Bash debugger to debug your scripts. A simpler option is to use the DEBUG trap: #!/bin/bash function prompt { if [[ -n "$BASH_COMMAND" ]]; then echo About to run \'$BASH_COMMAND\' read -p 'Continue [Y/n]?' CONT if [[ "$CONT" = "n" || "$CONT" = "N" ]]; then echo Exiting prematurely exit 1 fi fi } trap ...


0

You can't do exactly this with the default *nix permissions model. If someone can create a directory within /some/path, they can create any directory within that path. You might be able to use a permissions framework on top of that such as SELinux or AppArmor, or you could create a suid binary which only does this one job of creating a directory using the ...


-1

The things you want to do in those .'ed scripts are changing the shell process; so you need to call them from the shell process; which means either aliases, or their more powerful brothers shell functions. This means you have to do some setup in .profile or equivalent. The alias trick is sort of simplistic: alias mytool1=". /my/library/mytool1.sh" Can ...


3

With Perl you can make it like as shown: echo a2b3c4 | perl -pe 's/(\D)(\d+)/$1x$2/ge' aabbbcccc


0

I would change your variable around some. I messed with this 'yesterday' thing today as well.. YESTERDAYS_DATE=$(date -d "-1 day" +"%Y%m%d") echo FILENAME$YESTERDAYS_DATE.txt output: FILENAME20190818.txt


0

Easy shell implementation: #!/usr/bin/env bash char="" count="" echo "$1" | while read -n1 -r c; do if [ "$char" = "" ] then char="$c" continue fi if [ "$count" = "" ] then count="$c" for i in $(seq 1 "$count") do printf "%s" "$char" done char="" count="" continue fi done ...


3

$ perl -e 'my @F=split //, shift; for my $i (0..@F) { print $F[$i] x $F[++$i]}; print "\n"' A2B3C4 AABBBCCCC This splits the input so that each single character becomes an element in an array (@F). Then, using perl's string multiplier operator (x) it prints every even-numbered element (starting at 0) a number of times equal to the ...


1

i usually use i.e. var1=`cat file` var2= someother; $host $port echo $var1 $var2 |telnet $host $port So in your case i would give telnet { while read -r line; do var=`awk -v var1="^$line" -F "|" '$1~var1{print $1 }' sort-address-name-ip.txt | awk -v var2="$line$" '$0~var2' ` var3=`awk -v var1="^$line" -F "|" '$0~var1{print $2 }' sort-address-name-ip....


0

Done in 2 steps Tested and worked fine in both scenarios a. cp orginalfile fileneedto_be_changed'(Need to do only one Time) orginalfile=====>which supposed to be changed b. differencecount=`awk 'NR==FNR{a[$0];next}!($0 in a){print $0}' orginalfile fileneedto_be_changed|wc -l` if [ $differencecount -eq 0 ] then echo "NO changes in file" else echo "...


1

If you want to copy /data/directory on Linux so that a copy of it will appear as \\192.168.1.1\share\directory on Windows, then perhaps this command should do the job: smbclient -W WORKGROUP --user='admin%admin$123' -c "lcd /data;recurse;mput directory" "//192.168.1.1/share" Rationale: to copy a directory with its contents, you'll need to enable recursion ...


0

if you are checking changes in a git repo, you can use: #!/usr/bin/env bash diff="$(git diff | egrep some_file_name_or_file_path | cat)" if [[ -n "$diff" ]] ; then echo "==== Found changes: ====" echo "diff: $diff" exit 1 else echo 'Code is not changed' fi


1

Not sure what you're going for here... but it sounds like you want awk (or cut) after the grep to only print the sums. But then a checksum of checksums to ensure you have all the files? Is that the end result you wanted? BTW, I'm almost positive the glob md5sum * returns a random order, so you probably want a sort in there somewhere to ensure it's the same ...


0

Here are some alternatives, along the lines of terdon's answer, that try to make it easier to handle SQL*Plus' output given that you are trying to fetch it into the shell variable ID_VAL. By default, SQL statements executed in SQL*Plus produce formatted reports, made of columns whose width will depend on the respective data types. This will lead to some ...


0

foo () { awk '{ print $2 }' /proc/mounts | while read -r mountpoint; do for pattern do if [[ $mountpoint == $pattern ]]; then printf '%s:\t%s\n' "$pattern" "$mountpoint" break fi done done } This bash function parses out the second column, the mount point, from /proc/mounts ...


1

md5sum * | sort -k1 | uniq -w 32 -d | cut -d' ' -f3 | xargs -I{} sh -c 'rm {}' take all the md5 values sort them so dupes are sequential for uniq run uniq to output dupes only cut the filename from the line with the md5 value repeatedly call delete on the filenames


2

sh can only do integer arithmetic so you have to use something else, like bc (or a language that can do non-integer arithmetic such as awk or perl). To use bc, you first have to convert the %H:%M:%S.%3N format to seconds (including the decimal fraction) and then pipe that into bc. For example: #!/bin/bash epoch='1970-01-01' len1='00:01:01.111' len2='00:...


1

grep | xargs is not the best tool for this sort of thing, because it can't safely deal with complex filenames. However, you have a couple of options if your filenames don't contain line feeds: grep -rl "stringToReplace" * | xargs -I {} sed -ie 's/stringToReplace/newString/' {} This works with any (XSI) POSIX-compatible xargs. -I {} forces single-line ...


6

For the same reason sudo --login echo '$HOME' Doesn't output $HOME, but the content of the $HOME variable (of the target user, as set by sudo). In your case, it's not because sh -c doesn't expand the positional parameters, but because the $0, $1, $2 were already expanded (by the login shell) by the time sh was started. What is more surprising here is why ...


2

Fun, but probably not the best. temparr=( b{a,e,i,o,u} c{a,e,i,o,u} d{a,e,i,o,u} ) echo "${temparr[@]}"


3

I will ignore exec and -i as it is not clear what you are asking with respect to these. However to cd and sudo, then ( cd «a directory»; sudo «a command» ) The parenthesis () create a sub-shell, cd is a built-in, then the command sudo or whatever. So process count is same as env. sudo also manipulates environment variables, so may not be a need for env ...


Top 50 recent answers are included