Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

Shell Scripting

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

Have the text file below:

File output.txt

4-character_string_without_space:

1. A few lines of text without character ":"

4-character_string_without_space:

4-character_string_without_space:

4-character_string_without_space:

2. A few lines of text without character ":"
.....

Is there any way to remove the lines with "4-character_string_without_space: and the immediate blank line" if no text follows them? For example.

Original text file:
ABCD:

line1
line2
line3

ABDD:

DDBA:

line5
line6
 
....

Wanted output:
ABCD:

line1
line2
line3

DDBA:

line5
line6
 
....

ABDD: should be removed. Any gurus, is there any concise way to do that? Thanks a lot.
0
Free Tool: Path Explorer
LVL 10
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Morning folks, I need a script creating to be run on Server 2012 to look at a few thousand folders and extract the folder permissions to allow me to analyse this in excel.

The reason for this is we are in the process of consolidating (literally) hundreds of legacy domains down into a smaller forest, and we need to understand what folder permissions are around to help get it down.
0
Please provide me with the correct syntax for granting a user full access to another user's Office 365 calendar by using the Office 365 Power Shell.

For example this command grants a single user full access to everyone's calendar within Office 365.

How can this power shell command be modified to grant a single user access to another user's Office 365 calendar?

Get-Mailbox | ForEach-Object {Add-MailboxFolderPermission $_":\Calendar" -User msmith@company.com -AccessRights Owner}

Open in new window

0
I have a main shell script that gets parameter values from an external file.  I need to start looping through a particular set of parameter values and can't figure out how to make it all come together.  

In test_main_script, I have successfully used/called(?) the external parameter file by putting
. env.vars

Open in new window

at the beginning of the file.  

But now I need to loop through a set of values, and I'm putting the list of values in a text file.  I'm trying to use/call the external parameter file once for each value in the text file.  

Here are the files that I have created.  The loop part almost works (it leaves off the last row), but whereas previously the values correctly passed from env.vars to test_main_script.ksh (before I added the loop), now they don't get passed.  

What am I missing, to get the values to correctly pass from env.vars to test_main_script.ksh?

My background is Oracle development; I'm still learning shell scripting.

Thank you,
Cali

##### test_main_script.ksh #####

#!/bin/ksh -x
# main script
while read -r a b; do
  ./env.vars $a $b

  export start_date
  export stop_date
  export row_id
  export row_name
  echo start_date=${start_date}
  echo stop_date=${stop_date}
  echo row_id=${row_id}
  echo row_name=${row_name]
  echo 'This is the main script'
done < test.txt

exit 0

##### test.txt #####

12 first
345 second
67 third

##### env.vars #####

#!/bin/ksh -x
export start_date='20170703'
export stop_date='20170704'
export row_id=$1
export row_name=$2

Open in new window

0
Hi Experts,
Hope you are doing well. I am trying to run a command from linux to windows using winexe.

I am able to fetch information from windows systems using winexe like the example below wherein the powershell runs remotely and gets information into $x

x=`winexe -U user%pwd //vservername 'powershell.exe Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty NumberOfLogicalProcessors'`

In some systems the command gets stuck in the remote system and does not come back, I would like to add a timeout to the above command, I tried this

x=`timeout 10 winexe -U user%pwd //vservername 'powershell.exe Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty NumberOfLogicalProcessors'`

but does not work.

Could you please help me with putting a timeout such that the command comes back if it gets stuck.

Thanks
Amrith
0
Dear Experts.

I'm using the following Backup Script:

#!/bin/bash
# directory to put the backup files
BACKUP_DIR=/backup

# MYSQL Parameters
MYSQL_UNAME=bckpusr
MYSQL_PWORD=**********

# Don't backup databases with these names 
# Example: starts with mysql (^mysql) or ends with _schema (_schema$)
IGNORE_DB="(^mysql|_schema$|sys)"

# include mysql and mysqldump binaries for cron bash user
PATH=$PATH:/usr/bin

#==============================================================================
# METHODS
#==============================================================================

# YYYY-MM-DD
TIMESTAMP=$(date +%F)

function mysql_login() {
  local mysql_login="-u $MYSQL_UNAME" 
  if [ -n "$MYSQL_PWORD" ]; then
    local mysql_login+=" -p$MYSQL_PWORD" 
  fi
  echo $mysql_login
}

function database_list() {
  local show_databases_sql="SHOW DATABASES WHERE \`Database\` NOT REGEXP '$IGNORE_DB'"
  echo $(mysql $(mysql_login) -e "$show_databases_sql"|awk -F " " '{if (NR!=1) print $1}')
}

function echo_status(){
  printf '\r'; 
  printf ' %0.s' {0..100} 
  printf '\r'; 
  printf "$1"'\r'
}

function backup_database(){
    mkdir -p $BACKUP_DIR/$TIMESTAMP
    backup_file="$BACKUP_DIR/$TIMESTAMP/$database.sql.gz" 
    output+="$database => $backup_file\n"
    echo_status "...backing up $count of $total databases: $database"
    $(mysqldump $(mysql_login) $database | gzip -9 > $backup_file)
}

function backup_databases(){
  local databases=$(database_list)
  local total=$(echo 

Open in new window

0
Hi All,

Greetings...

According to my work, I need to zip files present in a folder using batch script without using any 3rd party software.

I tried with below code ,but getting the error.error also attached below.

Any help regarding this would be highly appreciated.
'Get command-line arguments.
Set objArgs = WScript.Arguments
Set FS = CreateObject("Scripting.FileSystemObject")
InputFolder = FS.GetAbsolutePathName(objArgs(0))
ZipFile = FS.GetAbsolutePathName(objArgs(1))

'Create empty ZIP file.
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)

Set objShell = CreateObject("Shell.Application")

Set source = objShell.NameSpace(InputFolder).Items

objShell.NameSpace(ZipFile).CopyHere(source)

'Required!
wScript.Sleep 2000

Open in new window


This code is present in zip.vbs file. We have to zip the files into Outputfile.zip file.
in command prompt  , I have entered below command

C:\Users\abc>Cscript zip.vbs input path  output path\OutputFile.zip

While executing this ,I got below error. " Path not found error" for both the input and output file path.

It will be helpful if anyone corrects me the mistake which I made in this script.
2
i'll need a Shell script that scans thru creation dates of all patches (ideally only the security ones but
if this is not possible, then all patches) installed in an RHEL 7 server, get the latest one, compute
the difference from today's date & give the difference in number of days & if the difference is
more than 90 days, echo out a message, "It has been more than 90 days since last patch)

Purpose is to check the last patch date & remind Linux admins.  Believe RHEL releases patches
at least every 3 monthly?
0
Hello ,

I want to appy a system command with arguments from variables but i could not find an example any body has experience about this ?


This is what i want to do
system("/bin/bash  /etc/a.sh   %d %d",val1,val2);
0
Hi,

I am writing a script which connects via server remotely and run the sql script but the thing is i am passing process ids as paramerters  to kill the process of remote server here is the way i am sending

shell script :
echo "Pid :" ${pid[$i]}
      output=$(ssh -o StrictHostKeyChecking=no oracle@$HOSTNAME -p 9292  "bash -l -c sqlplus @"</home/oracle/process.sql ${pid[$i] )

Following is the sql script :

/as sysdba
            whenever sqlerror exit sql.sqlcode;
            SET HEADING OFF;
            SPOOL processOutput.txt
       
            select DISTINCT
            s.CLIENT_IDENTIFIER
            from v$session s, v$process p, v$sql q
            where s.paddr = p.addr      
            

and p.spid IN ($1,$2)

           and s.sql_id = q.sql_id(+);
            spool off;
            exit;

getting  ERROR at line 5:
ORA-00911: invalid character

line refering the error is hilighted.
0
On Demand Webinar - Networking for the Cloud Era
LVL 10
On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Hello All,

Below script works fine and gets the output, I am planing to run this script against 50 Machines the output should have hostname/computername column. Thanks for help  

Import-module servermanager ; Get-WindowsFeature | where-object {$_.Installed -eq $True} | Select-Object name, d
isplayname, installstate

Open in new window

0
Every month  we wud like to sftp over  Win 7 n Win 10 patches (.msi  .msu, ??)  to about 20 remote PCs that are located in our supplier/service providers premises as these PCs are npt part of our corporate's AD/domain n we cant Rdp/remote to them for security reason.

Can anyone provide a batch or cmd scripts tt will scan for the presence of msi or msu (or any extensions tt MS patches may come in) in a folder (say c:\MSpat )  n will execute them in silent mode (ie dont need us to input/intervene) but dont reboot after patching.  Ideally, output logs ( >>) or error ( 2>>) to 2 separate logs.  Housekeep away the patch files
0
Hi Experts,

The issue i have is, i have to take all the .jar files from a particular location and i need to fetch those file names in an excel sheet along with the file size using shell script.
0
Hi Experts,
could you advise what is the best way to sort directories which has string with number prefix in bash please?

Scenario/Actual
DIR_NAME_Drop0
DIR_NAME_Drop1
DIR_NAME_Drop10
DIR_NAME_Drop2
DIR_NAME_Drop3
DIR_NAME_Drop4
DIR_NAME_Drop5
DIR_NAME_Drop6
DIR_NAME_Drop7
DIR_NAME_Drop8
DIR_NAME_Drop9


Expected
DIR_NAME_Drop0
DIR_NAME_Drop1
DIR_NAME_Drop2
DIR_NAME_Drop3
DIR_NAME_Drop4
DIR_NAME_Drop5
DIR_NAME_Drop6
DIR_NAME_Drop7
DIR_NAME_Drop8
DIR_NAME_Drop9
DIR_NAME_Drop10

Script for your reference
mkdir DIR_NAME_Drop2
mkdir DIR_NAME_Drop3
mkdir DIR_NAME_Drop10
mkdir DIR_NAME_Drop0
mkdir DIR_NAME_Drop1
mkdir DIR_NAME_Drop4
mkdir DIR_NAME_Drop5
mkdir DIR_NAME_Drop6
mkdir DIR_NAME_Drop7
mkdir DIR_NAME_Drop8
mkdir DIR_NAME_Drop9

Open in new window

0
I have been using this power shell command to create a text files that lists the currently installed programs on Windows 10 computers:

Get-WmiObject -Class Win32_Product | Select-Object -Property Name > C:\PCapps.txt

Open in new window


The problem is that this command lists only the names of the installed programs.

I would like to run a command that will display the complete list of everything that is displayed within the Programs and Features applet: Software name, publisher, installed on, size, & version.

What is the correct syntax of a command that will display all this information?
0
OS: AIX shell:ksh

i need a grep statement to give any  error for today's date and for specific time from a log file.

My grep statement should grep current date i.e. 7/19 and timing for 6 to 6:59 and finally for string as 'error' or 'Error'

e.g  log file content will be like

[7/19/17  6:01:26:611 CDT] XXXXX  error -911
0
I need to replace one of the tag attribute value from one file to other xml file. we need to update "0 58 40 * * ?" from ServiceContext.xml_pre_455 to ServiceContext.xml. we don't have xmlstarlet.

ServiceContext.xml_pre_455

<bean id="service_TriggerOfflineDBProducer" class = "org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref local="service_OfflineDBProducerJob" />
        </property>
        <!-- Schedule OfflineDB producer at 3:30 everyday, preferably after DIMP runs. -->
        <property name="cronExpression" value="0 58 40 * * ?" />
    </bean>


ServiceContext.xml

<bean id="service_TriggerOfflineDBProducer" class = "org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref local="service_OfflineDBProducerJob" />
        </property>
        <!-- Schedule OfflineDB producer at 3:30 everyday, preferably after DIMP runs. -->
        <property name="cronExpression" value="0 26 15 * * ?" />
    </bean>
0
I need to convert all files in a folder from binary named zone format to text zone format.

the command is

 named-compilezone -f raw -F text -o myzone.ch.hosts.text myzone.ch myzone.ch.hosts.binary

the present binary files are always named like "myzone.ch.hosts" - after conversion they should have the same name.

but how do i do that automatically for all files in the folder?

Thanks!
0
I have this rather simple shell script below and I see an error on line 8 below

What is wrong with my shell script?

set -x
for i
do
        echo $i
        outfile=$i_new
        echo $outfile
        cat $i | sed -e 's/STASIS //'   > $i_new
done
++ for i in '"$@"'
++ echo file1.xml
file1.xml
++ outfile=
++ echo

++ cat file1.xml
++ sed -e 's/STASIS //'
./removeStasis.sh: line 8: $i_new: ambiguous redirect


Here is my script:

set -v
set -x
for i
do
        echo $i
        outfile=$i_new
        echo $outfile
        cat $i | sed -e 's/STASIS //'   > $i_new
done
0
[Webinar] Lessons on Recovering from Petya
LVL 10
[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Hello,
with openldap you can define a max-password age: pwdMaxAge
Any ldap account that uses a password that was set before today-pwdMaxAge (in seconds) is considered expired.

Now on http://techadminblog.com/send-password-expiry-warning-openldap/

there is a script that can be run with crontab checking all ldap accounts and informing the affected users of an impending password expiry.

It checks if there are 3,2,1 today days left.

if [ "$DIFF" == `expr $MAXPWDAGE - 3` ]; then
 SUB="User $USERID password expire in 3 days"
 smail
 elif [ "$DIFF" == `expr $MAXPWDAGE - 2` ]; then
 SUB="User $USERID password expire in 2 days"
 smail
 elif [ "$DIFF" == `expr $MAXPWDAGE - 1` ]; then
 SUB="User $USERID password expire in 1 day"
 smail
 elif [ "$DIFF" == "$MAXPWDAGE" ]; then
 SUB="$USERID password will expire today at $EXTME UTC"

----
How can I change that part of the script  to inform the users that a password change is needed in less than 20 days, less than 10 days, today, or even has already expired?

does change "$DIFF" == `expr $MAXPWDAGE - 3` ->  "$DIFF" -lt  `expr $MAXPWDAGE - 20` the trick?

Reason we use openldap to handle external user accounts that are rarely used so informing the users that their pasword will expire in 3 days is too late - in most cases the password is often already expired when they call us about being unable to logon to our systems.

regards,
Tolomir
0
Hello,

  I would like to know if there is a way to create a Symlink-like file but with the difference that the file it points to gets executed when the link is read and the output is what I get from reading it.
  It should work on freebsd/linux.

Thanks

Best regards
0
We currently operate within a Citrix environment and publish a number of web applications by point to Internet Explorer with the corresponding website as the parameter.

We face an issue currently whereby if the browser is closed, the session remains active.

We need the session to logoff if the browser is closed.

With a previous version of IE (8 perhaps, but not entirely sure) we scripted this, however in current versions of IE this no longer works.

I guess a script that launches IE, and then monitors for its closure before issuing a logoff command would be ideal, but am open to alternative suggestions if there are better ways to achieve what we are looking for.
0
I have few excel and .rpt file which are updating daily basis, in my scenario i have to parse the files and some of the columns should be insert into MS access database. i am not sure how to start with. As per my manager i should use shell scripting to write the code but i am not sure which is the best way.

I need help in this any kind of help will be appreciated.
0
Hello Experts,

I have created an EFS Filesystem, I am trying to find a script which will give me the below

Input to script : EFS Filesystem ID
Output : {AZ targetIPAddress}

we dont have aws dns, so we are manually mounting using IP address...Here are the steps, I have...

1. The below command will give the Subnet and IP address
# $ aws efs describe-mount-targets --file-system-id fs-e10c82b2 --query 'MountTargets[*].[SubnetId,IpAddress]' --output text
OUTPUT : {SUBNET IPADDRESS}

2. The below command will give me AZ for the subnets
$ aws ec2 describe-subnets --subnet-ids subnet-9456320b --query 'Subnets[].AvailabilityZone' --output text
INPUT :SUBNET
OUTPUT : AVAILABILITY ZONE

How do I combine these 2 scripts to get
- AVAILABILITYZONE IPADDRESS

Please assist
0
I heard iOS is tailored from FreeBSD so I'm hoping to be able to do something like
"ps -ef |grep email_client_process"
if it's not there, then restart it.

Reason is our MobileIron email+ client kept getting killed by iOS as iOS sees it
as a 3rd party/foreign process.

any chance of doing this on an MDM controlled device?
0

Shell Scripting

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.