Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x

Shell Scripting

10K

Solutions

6K

Contributors

The term 'shell' refers to a general class of text-based command interpreters most often associated with the UNIX and Linux operating systems. Popular shells include Bourne, Debian Almquist (dash), Korn (ksh), Bourne Again (bash) and the C shell family (csh). Some view the DOS 'cmd' prompt as a minimal shell of sorts. It is also possible to install Cygwin on Windows and emulate a full Unix environment with complete shell capabilities. Terminal emulators, such as xterm, GNOME Terminal and OS X Terminal, can be used to access shell.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts,
I am having trouble stripping only the last character and second last, of a variable

before sed:
107005075456+
1019918397440+
182400823296+
53550772224+
1810193428480+
+

expected result:
107005075456+
1019918397440+
182400823296+
53550772224+
1810193428480

we tried sed -e 's/\+$//' but its stripping all + but I want to get rid of only the last + and the one on the second last line

Could you please help!
0
Free Tool: IP Lookup
LVL 11
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hi Experts,

I am trying to get total disk size from multiple servers and wmic is what I am trying to use.

However I am unable to add the results coming from wmic to find the total disk space. I am trying something like this:

sizelist=`winexe -U rpega/$u%$p //$i "WMIC LOGICALDISK where drivetype=3 get size"|sed s/^M//g`
echo $sizelist > sizelist.file
sizearr=($sizelist)

counter=1
result=0
re='^[0-9]+$'
        while [ "${sizearr[$counter]}" != "" ]; do
          if ! [[ ${sizearr[$counter]} =~ $re ]]; then
        result=`expr $result + ${sizearr[$counter]}`
        fi
        counter=$(expr $counter + 1)
        done

echo "the total size is $result"

Open in new window


i am very bad at shell scripting so the above code may look weird. Please feel free to change it, i would like to be able to add the results coming from wmic command to get total disk allocation size.

The wmic command gives results like this:

Size
107005075456
966230274048
214612045824
53550772224
1429227958272

and I would like to be able to add these numbers and get the result.

Thanks
0
I have a csv file in wondows and I have installed GOW to allow me to use linux commands to split a file

I need to copy the header record and place that into each split file and have that split file go to a split directory

so my file is here>>
data/current load/testing.csv


I would need to have it split to the following directory
data/current load/spit/

and then I need to make sure I have the header record copied over to each split file

what I have so far is
so here is my input csv file name testing.csv

head -n 1 "F:data\current load"\testing.csv > header_file

tail -n +2 "F:data\current load"\testing.csv > data_file

split -d --lines=1000 "F:data\current load"\data_file "F:data\current load\split"\data_file

at this point i have created all the split data files


ls split\data*

my set of instructions are for each file

copy header_file split\*

cat split\data_file16 >> split\header_file

rename split\header_file split\data_file16.csv

rm split\header_file


so first I am looking for a way to read all the data files names to be able to loop through my second part of the process

and ideally I am sure there must be a single line to do the same thing that I want to do using some sort of awk command
0
hello experts
i am using powershell to start up plink.exe ssh to my network device and promote some commands, see below please.
$Plink = (${env:ProgramFiles} + "\PuTTy\plink.exe")
$commands = "d:\commands.txt"
& $Plink 192.168.18.2 -l admin -pw ******** -m $commands

and below is the content of commands.txt
conf t
int gig 0/0
shu

but i can't get it works, if you put only one command in the txt file or without -m parameter with only one command, it works, could you help me fix it and let me know what is the correct command text file format should be?

thank you
0
Hi experts.
Would like to save the content to a file rather than displaying it from python script. Since I'm new to python pls help me
Have attached a python script. right now it prints the content to stdout.

# I think, this line
self._display.display(json.dumps(output, indent=4, sort_keys=True))

Open in new window


Is it possible to have a variable declared for directory for json file location and write the file there?

Source File location:
https://codeclimate.com/github/ansible/ansible/lib/ansible/plugins/callback/json.py

thanks in advance.
json.py
0
Hi,

I would like to use grep and and sed to replace string to something else .

Eg :

When i use grep, there are 97 result :

root@svr51 [/home/xxx/public_html/akaunting]# grep -lir "ini_set" ./* | wc -l
97

I would like to replace "ini_set" found in those file to "//ini_set" , to comment/disabled that line.

Anybody can help to construct full grep and sed command ?

Please let me know also the location where i should run that command to avoid it to replace file in wrong location.

Thank you.
0
Have a list of files in a directory and the only difference in the file name is the date/time stamp.  The first 4 values of the file name will be the same for all files except the date/time and 6th value.  Would need to check the 6 value to see if it is the same as another file because the only difference would be the date/stamp.  If the 6th value is the same then move to a dup directory else move to another directory.

Would like to use a file to store the 6th value in a file and check each file against this file.

This is what I have.  Not sure if this is a good approach.

File name  --  parm1_parm2_parm3_parm4_date/time_parm6.csv

      FILELIST=`ls -1 2> /dev/null`
  for file in $FILELIST
do
      messageid=`echo $file | cut -d "_" -f6`
      echo ${messageid} >> /app/tmp/msg_list.txt
if      [ ` grep -c -f /app/tmp/msg_list.txt $messageid ` -ne 0 ]
      then
            mv $file  /somedirectory
      else
            echo mv $file /dup_directory
fi            
done
0
Good day,

I have this bash script where i can generate a from-to ip range.  

However I need something similar in kornshell and need it to generate it's own /24 network with random hostnames from any single ipadress input
 
So like 192.168.1.5 will generate the full 192.168.1.1/24 with hostnames.



#!/bin/bash
#
# Convention for octets:  A.B.C.D

# Variable setup section...
#
# Split up IP addresses into seperate variables for each octet
IPLO=(`echo "$1" | awk '{split($1,a,"."); print a[1]" "a[2]" "a[3]" "a[4]}'`)
IPHI=(`echo "$2" | awk '{split($1,a,"."); print a[1]" "a[2]" "a[3]" "a[4]}'`)
#
# Put array contents into nicely named vars for less confusion
#
OCTA=${IPLO[0]}
OCTB=${IPLO[1]}
OCTC=${IPLO[2]}
OCTD=${IPLO[3]}
OCTAHI=${IPHI[0]}
OCTBHI=${IPHI[1]}
OCTCHI=${IPHI[2]}
OCTDHI=${IPHI[3]}
OCTDMAX=255             # Max default value for D Octet to loop to
FINISHED=0              # Variable used for loop state checking

# Syntax sanity check; check all vars are populated etc
for i in 0 1 2 3
do
        if [ -z "${IPLO[$i]}" ] || [ -z "${IPHI[$i]}" ]; then
                echo "Usage: $0 [from ip] [to ip]"
                exit 1
        elif [ "${IPLO[$i]}" -gt "255" ] || [ "${IPHI[$i]}" -gt "255" ];then
                echo "One of your values is broken (greater than 255)."
                exit 1
        fi

done

# Until FINISHED variable is set to 1, loop the loop.
# FINISHED var is used to determine when done as the …
0
I wrote a simple script to display installed programs. It works on the local machine just fine - grabs the programs, lists them alphabetically, great. When I try to run it on a remote PC, the script finishes but there is no output. No error, but nothing displayed. I tried putting Write-Host in various places, but no joy. I would like to be able to retrieve this information without having to write it to a file on the local machine, and then open the file to read the info. Any hints? Also not sure if the invoke-command is needed.


$Computername = Read-Host -prompt ("Which PC would you like to Inventory installed software on?")
$Credential = Read-Host -prompt ("What domain and username would you like to Authenticate with?")
$s = New-PSSession -ComputerName $Computername -Credential $Credential
Invoke-Command -Session $s -ScriptBlock {Get-WMIObject -Class Win32_Product -Computername $Computername | Sort name | Format-Wide -Column 1 -passthru}
0
I want to log into a website using a username and password, so I copied the following code and executed. In result the webpage is opening but its not logging into the webpage and getting the following error.

Any suggestions?

$ie = New-Object -com InternetExplorer.Application 
$ie.visible=$true
$ie.navigate("url") 
while($ie.ReadyState -ne 4) {start-sleep -m 500} 
$ie.Document.getElementById("ctl00_username").value = "abcdef" 
$ie.Document.getElementById("ctl00_password").value = "123456" 
$ie.Document.getElementById("ctl00_login").click()
start-sleep 20 
$ie.Document.body | Out-File -FilePath C:\Users\averm\Documents\adi\test\web123.txt 

Open in new window


Exception from HRESULT: 0x80020101
At line:7 char:1
+ $ie.Document.getElementById("ctl00_usernamerequiredvalidator").value  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
 
Exception from HRESULT: 0x80020101
At line:8 char:1
+ $ie.Document.getElementById("ctl00_passwordrequiredvalidator").value  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
 
Exception from HRESULT: 0x80020101
At line:9 char:1
+ $ie.Document.getElementById("ctl00_login").click()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Open in new window

0
Keep up with what's happening at Experts Exchange!
LVL 11
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Hi Experts,

I trying to create a shell script.

I want to read words from one file and search them in another file. If any word not found then send email. If words found then nothing to do.

If multiple words not found then send that information as a single email rather than multiple emails for each word not found.

File1 contains process names and file2 contains current running processes.

Thanks in Advance!

Sat
0
Hi, my organization has contacts globally, I only need contacts for America region usually I use get-contact or get-contact - identity for all contacts or specific contact is there any script for a specific region? thanks
0
I have roughly 1000 files from a website on my local hard disk.  I want to determine if any of these files have:
http://localhost

Open in new window

on any line, except skip the ones that have:
comment="http://localhost

Open in new window


Thus, if there are any "HREF="http://localhost" entries, it would show up, or any "SRC="http://localhost", it would show up in the results.

Any easy way to do this?
0
Hello,

what I would like is a batch file that will get the folder structure of the drive into a menu structure so that you can select the folder you want to go into, and once you select a folder from the menu, the subfolders of that folder would then be listed in a menu as well, and so on and so forth as deep into the folder structure as you want to drill down to. And in each menu would have a "backup current folder level" and a "list all contents of current folder" and if possible include a "go to previous folder" option.

 Basically I would like to run the batch file and be given a menu of the folders only of the c drive, then be given an option to either backup the current folder, list the files of the current folder in case I wanna to only backup one file from that folder, or select a subfolder and then be given the same options with the addition of the go to previous folder option for subfolders.

 I've tried and tried to write something like this but I'm not a strong batch script writer and just can't get anywhere with it.

 Thank you very much in advance for your help,
Ryan
0
Hi there,

I'm trying to dynamically create this string in a variable so that I can then run "eval" on it and run the command remotely on another Linux VM.

ssh oracle@10.41.22.69 "md5sum /data/oracle/dpdump/onegeo/ONEGEO20171214.DMP | awk '{ print \$1 }'"

I can get the string working until the "awk" part and then no matter what I try, I keep getting errors when trying to properly create the rest of the string with single quotes.  The double and single quotes in the string are all required.  

I tried this but it didn't work, what am I missing?
md5command='ssh oracle@10.41.22.69 "md5sum /data/oracle/dpdump/onegeo/'$DMPfilename' | awk '\'{ print \$1 }\''

Any help would be appreciated!!

Thanks,
- Christian
0
hello sorry for my english

is a script to upload files juste me i would like detect the new files in forlder and upload files or folder in my ftp in cron job im a noob in script shell and i need help ty :)
#!/bin/sh
HOST='ftp.example.com'
USER='yourid'
PASSWD='yourpw'
FILE='file.txt'

ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
binary
put $FILE
quit
END_SCRIPT
exit 0

Open in new window

0
I am new to the Perl syntax but have used OOP from Pascal, to C++ to C#.

Can you give me an example of the syntax for using OOP in Perl?

Thanks.
0
I understand Perl is part of my Mac OS, but I hear I would be best served to ensure any programming (learning) in Perl should be isolated so as not to upset the functioning of my El Capitan system.

What kind of installation shall I make to ensure the Perl I access from Mac Terminal does not touch any system files?

Thanks.
0
Hi
I like to parse my command line arguments in a function.
The following script does not work
var1=$1
var2=$2
DB_UserName=
DB_Password=

usage(){
    echo "usage: sqlexed [-u username ] [-p password]" 1>&2; exit 1;
}

processparameters(){
while getopts ":s:p:" o; do
    case "${o}" in
        s)
            DB_UserName=${OPTARG}
            ;;
        p)
            DB_Password=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${DB_UserName}" ] || [ -z "${DB_Password}" ]; then
    usage
fi
}

Main() {
processparameters $var1 $var2
}
Main | tee autosql.log


Not able to process the command line arguments. What do I have to change to be able to parse them in a function_
thx
0
Hire Technology Freelancers with Gigs
LVL 11
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Hi
with a unix command I want to replace all occurrences in a text file
1. LF by CRLF
2. LF by NL
3. CRLF by NL
5. NL by LF

Where
Abbreviation      hexvalue      decvalue      Escape sequence
LF                      0A                10               \n
CR LF                0D 0A      13 10      \r\n
CR                        0D              13              \r
RS                       1E                30      
LF+CR                 0A 0D      10 13      \n\r
NL                        15                  21      \025


Many thanks
0
I need my website to extract the data from a PDF and generate a CSV file. And I hope to do this on the front end, inside the client browser. But, if required, I could to this extraction on the back-end.

The PDF would be a month merchant credit card statement. The data I would extract to a CSV would be the numerous transactions.

What web technology can do this? And without human intervention.

Thanks.
0
My database team supports approximately 70 software developers.  We have inherited many database maintenance utility scripts, that automate several routine database activities.  In our dynamic software development environment we all developers to choose the version of the database schema to run their code against.  

Our development environment is a unix variant, i.e. Oracle Solaris.  When developers install new versions of the application they must associate the correct version of the database schema.  So our team has devised a script to handle this chore for each developer.  The problem is this script generates a log file and the naming of this log files sometimes gets missed name with a previous version.  

Log file mechanics:

•      Log file is named same as script being run
o      Log file name is identical to script with a “g” plus number extension
o      Example:  script=DumpRecord logfile=DumpRecord.g1
•      Print all current active variables
•      Print all echo statements in script


This database utility script is run at a high rate of frequency almost concurrently by some users.  The script allows J2EE software developers to update their individual schemas to run against their application in their isolated environment.  Developers are separated by Oracle Solaris Zones, however supported by a single database.  

Any ideas to avoid naming conflicts?
0
Hi there,

I'm trying to run a bash script remotely on an Oracle server, but when I do I get errors.  The script runs just fine locally.

Command from server1 to server2:
ssh oracle@10.41.22.69 /home/oracle/juletest2.sh
Error on server 1:
Error 6 initializing SQL*Plus
SP2-0667: Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory


Same Command on server2:
oracle@VMUSDevORA01 ~]$ ./juletest2.sh

PL/SQL procedure successfully completed.


Contents of juletest2.sh:
#!/bin/sh
sqlplus -L -s system/SysOra1234@cloud_dev @cleanonegeo



I'm assuming it's because the ORACLE_HOME variable hasn't been set since I'm running it remotely, but what is a workaround so that I can run this script remotely?  What should I include in the juletest2.sh script to get it working?
0
Greeting Experts,

I need help creating PowerShell script to read the name multiple files (over 2,000 files names) in a file directory and then import that information into a ".csv" document. Can somebody help me with this task...
0
I am writing shell script to create PV,VG,LVM and mountpoint and FS.

1. I am getting not-root disks using below command

PDEVICE=`lsscsi --device | grep -v "\:0\]$" | awk '/dev/{for(i=1;i<=NF;i++)if($i~/dev/)print $i}'`

Open in new window


2. Getting the PV's and checking whether the specific PV has attached to any VG or not as below.

VDEVICE=`/sbin/pvs | egrep -iv "(rootvg|PV)"  | awk '{print $1}'`

Open in new window


3. After that comaring these two arrays which PV's are not added to VG so that i am trying to add the missed devices to VG but some logic i am missing here ... can any one help in this ASAP please.

#! /bin/bash



PDEVICE=`lsscsi --device | grep -v "\:0\]$" | awk '/dev/{for(i=1;i<=NF;i++)if($i~/dev/)print $i}'`

echo ${PDEVICE[@]}


VDEVICE=`/sbin/pvs | egrep -iv "(rootvg|PV)"  | awk '{print $1}'`


echo ${VDEVICE[@]}

echo "Comparing the both the PV values"

for i in "${PDEVICE[@]}"
 do
    for j in "${VDEVICE[@]}"
 do
     if [ "${i[@]}" != "${j[@]}" ]
     then
      echo "${i[@]}"
     else
       echo "${j[@]}"
fi

done
done

Open in new window

0

Shell Scripting

10K

Solutions

6K

Contributors

The term 'shell' refers to a general class of text-based command interpreters most often associated with the UNIX and Linux operating systems. Popular shells include Bourne, Debian Almquist (dash), Korn (ksh), Bourne Again (bash) and the C shell family (csh). Some view the DOS 'cmd' prompt as a minimal shell of sorts. It is also possible to install Cygwin on Windows and emulate a full Unix environment with complete shell capabilities. Terminal emulators, such as xterm, GNOME Terminal and OS X Terminal, can be used to access shell.