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

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
Want to be a Web Developer? Get Certified Today!
LVL 9
Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

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 all i am managing email server ,i have user data in mysql. group list in sympa and user detail in active directory. if i want to romove any user from multiple group i do it manually one by one from all group,i want to make it automated through shell script,please suggest me best possible script to remove a user from multipe group and  from sympa,mysql, and ldap at same time.
0
Hey there,

I have an Exchange 2016 Hybrid setup with O365. All active users will be in the cloud, however terminated users will be migrated back to on prem and either left in the database for a term or exported to a PST. What I'm trying to do is to get my powershell script to pause until the batch completes and then continue on with some other tasks. I am aware of the Out-Null option but I don't think that's going to work in this case, as I need to confirm progress/completion after querying the status. I thought about using an Outlook rule that kicks off the remainder of my script after the migration notification is sent out but that relies on an outlook profile. Is it possible to do what I'm looking for or do I need something else in play here?

Thanks!
0
Basically I need to run the script with paths related to the shell script file location, how can I change the current directory to the same directory as where the script file resides?
0
according to my work,I have number of pdf files present in one folder .I need to merge all the files into a single pdf  file  based on last modified time stamp. Means first modified pdf file as first and then the rest.
I tried with the below code.

@echo off
setlocal enableextensions disabledelayedexpansion

set "root=%cd%"

>"output.pdf" (
    for /f "tokens=1,2,*" %%a in ('
        robocopy "%root%\." "%root%\." *.pdf /l /s /is /ts /ndl /njh /njs /nc /ns
        ^| sort
    ') do (
     echo( %%~nc
     for /f "tokens=1-3 delims=/" %%d in ("%%a") do echo %%f/%%e/%%d
     type "%%~fc"
    )
)




But it is producing output pdf which contains only one file which is  modified lastly.
Could you please help me to solve the issue.
Thanks in Advance..
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
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
Free Tool: ZipGrep
LVL 9
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

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

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 I have a  data like below format

Site	Variable	Units	Model	29/00Z	29/06Z	29/12Z
CQT	500mbHeight	dm	MASS	588.4	589 	588.9
CQT	500mbHeight	dm	NAM	589.4	589.5	588.2

Open in new window


How can i transpose as one below (like repeat first 4 columns for transpose of each row after 4th column
CQT	500mbHeight	dm	MASS	29/00Z	588.4
CQT	500mbHeight	dm	MASS	29/06Z	589
CQT	500mbHeight	dm	MASS	29/12Z	588.9
CQT	500mbHeight	dm	NAM	29/00Z	589.4
CQT	500mbHeight	dm	NAM	29/06Z	589.5
CQT	500mbHeight	dm	NAM	29/12Z	588.2
CQT	500mbHeight	dm	NAM	29/18Z	589.6

Open in new window

0
hi experts
could you help with below please

Sample string for this question
Could not find '/dir1/dir2//dir3/null_component_deploy.properties'
Could not find '/dir1/dir2//dir3/valid_file.properties'

1. how to ignore line 1
2. but catch line 2



Existing sample string/regex rule that experts exchange helped me which is working fine only for reference
/tmp/path - No such file or directory.
/tmp/shm - No such file or directory.
/dir1/validate_path - No such file or directory.

Working regex to exclude first two lines but catch the third line
/^(?!.*(tmp|log|shm))(.*No such file or directory.*)$/
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
On Demand Webinar - Networking for the Cloud Era
LVL 9
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,
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
Hi Im trying to display the output of the shell script in php.

When user login to the page it have to get the username and it should be passed to the shell script and that shell script output should be print on the webpage.In php the shell script is not getting executed

Please help me to make this.

PHP:-
<?php
session_start();
if(isset($_SESSION['username']))
{
$username=$_SESSION['username'];
$result = shell_exec('./get.sh >> temp.log');
echo "<pre>$result</pre>";
echo "<div id='User' style='float:right;color:#0000FF;' 'font-weight:bold;'>Welcome , " . $_SESSION[$result]. " </div>";
}
?>

Open in new window

Shell script:-
grep -A 1 "$username"  /mnt/eseesn60/ee_groups_see/ee_magicdraw/bittu/user.txt > /mnt/eseesn60/ee_groups_see/ee_magicdraw/bittu/get.txt
egrep -Ri ',' /mnt/eseesn60/ee_groups_see/ee_magicdraw/bittu/get.txt > /mnt/eseesn60/ee_groups_see/ee_magicdraw/bittu/getname.txt

Open in new window

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 three scripts that I run in PowerShell to get some information I need from remote workstations.   I would like this to be accomplished with just one script instead of three.   What I need to get from the remote stations is:

Hostname
IP Address
MAC Address
Operating System
Determine if the workstation is a 32-bit or 64-bit
Serial Number or Service Tag Number

I need to be able run these scripts using a list of either Hostnames or IP Addresses in a text file or csv file.  The reults also have to be exported to a CSV file.

Here are the scripts I use.   Not pretty, but they work.

Get-Content C:\Users\username\Desktop\IPs.txt |
  Where-Object { Test-Connection $_ -Count 2 -Quiet } |
  ForEach-Object {
    $IPAddress = $_
    Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled=TRUE' -Computer $IPAddress |
    Where-Object { $_.IPAddress -contains $IPAddress } |
    Select-Object @{n='IPAddress';e={ $IPAddress }}, MACAddress, DNSHostName
  } | Export-Csv C:\Users\username\Desktop\MACAddressReport.csv -NoTypeInformation

Open in new window


$computerlist = Get-Content C:\Users\username\Desktop\IPs.txt
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {   
        Get-WMIObject Win32_OperatingSystem -ComputerName $computer |
        select-object CSName, Caption | export-csv -Path C:\Users\username\Desktop\MACAddressReport-2.csv -NoTypeInformation -Append
    }
}

Open in new window


get-content C:\Users\username\Desktop\HostNames.txt |
   select-object `
     @{n = 'IP'; e = { [Net.Dns]::GetHostEntry($_).AddressList } },
     @{n= 'Name'; e = { $_ } } |
   Export-Csv C:\Users\username\Desktop\IPAddressReport.csv -NoTypeInformation

Open in new window


Any help would be much appreciated.
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

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.